Skip to content

Commit

Permalink
Github actions to create dist in server
Browse files Browse the repository at this point in the history
  • Loading branch information
karlosvas committed Jan 12, 2025
1 parent fb18f19 commit 6d81ae8
Show file tree
Hide file tree
Showing 37 changed files with 1,500 additions and 57 deletions.
82 changes: 82 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
name: Deploy to Vercel

on:
push:
branches:
- main

jobs:
deploy-frontend:
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v3

- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: "21.2.0"

- name: Install Vercel CLI
run: npm install -g vercel@latest

- name: List files in client directory
run: ls -la ./client

- name: Link and pull Vercel project for frontend
run: |
vercel link --yes --project ${{ secrets.FRONTEND_PROJECT_ID }} --scope ${{ secrets.VERCEL_TEAM }} --token=${{ secrets.VERCEL_TOKEN }}
vercel pull --yes --environment=preview --token=${{ secrets.VERCEL_TOKEN }}
working-directory: ./client

- name: Install frontend dependencies
run: npm install
working-directory: ./client

- name: Build frontend
run: npm run build
working-directory: ./client

- name: Deploy frontend to Vercel
run: vercel --token ${{ secrets.VERCEL_TOKEN }}
working-directory: ./client

deploy-backend:
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v3

- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: "21.2.0"

- name: Install Vercel CLI
run: npm install -g vercel@latest

- name: List files in server directory
run: ls -la ./server

- name: Link and pull Vercel project for backend
run: |
vercel link --yes --project ${{ secrets.BACKEND_PROJECT_ID }} --scope ${{ secrets.VERCEL_TEAM }} --token=${{ secrets.VERCEL_TOKEN }}
vercel pull --yes --environment=preview --token=${{ secrets.VERCEL_TOKEN }}
working-directory: ./server

- name: Install backend dependencies
run: npm install
working-directory: ./server

- name: Build backend
run: npm run build
working-directory: ./server

- name: List files in client directory
run: ls -la ./server

- name: Deploy backend to Vercel
run: vercel --token ${{ secrets.VERCEL_TOKEN }}
working-directory: ./server
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ dev
dist-ssr
client/dist
*.local
dist

# Editor directories and files
.vscode/*
Expand Down
1 change: 1 addition & 0 deletions client/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.vercel
7 changes: 0 additions & 7 deletions client/vercel.json

This file was deleted.

18 changes: 18 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,8 @@
"type": "GNU",
"url": "https://www.gnu.org/licenses/gpl-3.0.html"
}
]
],
"dependencies": {
"prettier": "^3.4.2"
}
}
1 change: 1 addition & 0 deletions server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.vercel
41 changes: 41 additions & 0 deletions server/dist/lib/firebase/firebase-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import dotenv from "dotenv";
dotenv.config();
////////////////////////////////////
import admin from "firebase-admin";
// Importa el archivo de credenciales de Firebase Admin
const serviceAccount = {
type: process.env.FIREBASE_TYPE,
project_id: process.env.FIREBASE_PROJECT_ID,
private_key_id: process.env.FIREBASE_PRIVATE_KEY_ID,
private_key: (process.env.FIREBASE_PRIVATE_KEY || "").replace(/\\n/g, "\n"),
client_email: process.env.FIREBASE_CLIENT_EMAIL,
client_id: process.env.FIREBASE_CLIENT_ID,
auth_uri: process.env.FIREBASE_AUTH_URI,
token_uri: process.env.FIREBASE_TOKEN_URI,
auth_provider_x509_cert_url: process.env.FIREBASE_AUTH_PROVIDER_X509_CERT_URL,
client_x509_cert_url: process.env.FIREBASE_CLIENT_X509_CERT_URL,
};
// Verifica si la aplicación ya ha sido inicializada
if (!admin.apps.length) {
try {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: process.env.FIREBASE_DB,
});
console.log("Firebase Admin initialized successfully");
// Verifica si se puede conectar a Firebase Auth
admin
.auth()
.listUsers(1)
.then(() => {
console.log("Successfully connected to Firebase Auth");
})
.catch((error) => {
console.error("Error connecting to Firebase Auth:", error);
});
}
catch (error) {
console.error("Error initializing Firebase Admin:", error);
}
}
export default admin;
12 changes: 12 additions & 0 deletions server/dist/lib/firebase/firebase-db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import admin from "firebase-admin";
// Función para obtener UID por correo electrónico
export const getUidByEmail = async (email) => {
try {
const userRecord = await admin.auth().getUserByEmail(email);
return userRecord.uid;
}
catch (error) {
console.error("Error fetching user data:", error);
return null;
}
};
69 changes: 69 additions & 0 deletions server/dist/lib/mailchimp/mailchimp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import dotenv from "dotenv";
dotenv.config();
/////////////////////////////////////////////////////////////
import mailchimp from "@mailchimp/mailchimp_marketing";
import axios from "axios";
// Id de la lista publica de contactos en Mailchimp
const listId = process.env.MAILCHIMP_LIST_ID;
// Id del grupo de intereses en Mailchimp
const groupId = process.env.MAILCHIMP_GROUP_ID;
// Api key de Mailchimp y prefijo del servidor
const mailchimpKey = process.env.MAILCHIMP_API_KEY;
const serverPrefix = mailchimpKey.split("-").pop();
// Configuracion del cliente de la API de Mailchimp marketing
mailchimp.setConfig({
apiKey: mailchimpKey,
server: serverPrefix,
});
// Convierte los errores de Mailchimp a objeto de javascript
function mailchimpErrors(error) {
return JSON.parse(error.response.text);
}
async function addInterestToCategory(interestCategoryId, interestName) {
const url = `https://${serverPrefix}.api.mailchimp.com/3.0/lists/${listId}/interest-categories/${interestCategoryId}/interests`;
const data = {
name: interestName,
};
try {
// El user puede ser cualquier string, no importa
const response = await axios.post(url, data, {
auth: {
username: "admin",
password: mailchimpKey,
},
});
return response.data;
}
catch (error) {
if (axios.isAxiosError(error) && error.response) {
throw { status: error.response.status, message: error.response.data };
}
else {
throw { status: 500, message: "Unexpected error occurred" };
}
}
}
async function deleteInterestCategory(interestCategoryId) {
const url = `https://${serverPrefix}.api.mailchimp.com/3.0/lists/${listId}/interest-categories/${groupId}/interests/${interestCategoryId}`;
try {
// El user puede ser cualquier string, no importa
const response = await axios.delete(url, {
auth: {
username: "admin",
password: mailchimpKey,
},
});
console.log(response.data);
return response;
}
catch (error) {
console.log(error);
if (axios.isAxiosError(error) && error.response) {
throw { status: error.response.status, message: error.response.data };
}
else {
throw { status: 500, message: "Unexpected error occurred" };
}
}
}
export { listId, mailchimpErrors, mailchimp, addInterestToCategory, deleteInterestCategory, groupId };
58 changes: 58 additions & 0 deletions server/dist/lib/resend/resend.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import dotenv from "dotenv";
dotenv.config();
import { Resend } from "resend";
// Configurar el cliente de Mandrill
const resend = new Resend(process.env.RESEND_API_KEY);
const admin = process.env.ADMIN_GMAIL;
// Enviar nota de contact us a el administrador
export async function submitNote(note) {
try {
return await resend.emails.send({
from: "no-reply@thefluentspanishhouse.com",
to: [admin],
subject: note.subject,
html: `
<p>The user <strong>${note.username}</strong> with email ${note.email_user} sent you this message:</p><br /><p>${note.note}</p>`,
headers: {
"Reply-To": note.email_user,
},
});
}
catch (error) {
console.error("Error sending email", error);
throw error;
}
}
// // Enviar email de nuevo estuidiante a el administrador
export async function submitEmailStudent(newstudent) {
try {
return await resend.emails.send({
from: "no-reply@thefluentspanishhouse.com",
to: [admin],
subject: `New student on TheFluentSpanishHouse ${newstudent.name} ${newstudent.lastname}`,
html: `<p>The user <b>${newstudent.name} ${newstudent.lastname}</b> wants to be a new student:</p><br />
<p>He wants to sign up for <b>${newstudent.class}<b/><p/>`,
});
}
catch (error) {
console.error("Error sending email", error);
throw error;
}
}
// Enviar email de nuevo comentario a el administrador
export async function submitEmailComment(note, originUrl) {
try {
return await resend.emails.send({
from: `no-reply@thefluentspanishhouse.com`,
to: [admin],
subject: note.subject,
html: `<p>The user <strong>${note.username} ${note.email_user}</strong> says:</p><br>
<p>${note.note}</p><br />
<p>From the post: ${originUrl}</p><br />User: ${note.email_user}`,
});
}
catch (error) {
console.error("Error sending email", error);
throw error;
}
}
27 changes: 27 additions & 0 deletions server/dist/middelware/token-logs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import admin from "../lib/firebase/firebase-config.js";
export async function log(req, res, next) {
// Registro de la solicitud
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
}
export async function verifyIdToken(req, res, next) {
// Validación de autenticación
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer "))
return res.status(401).json({ message: "Unauthorized" });
// Extrae el token de Firebase del encabezado de autorización, eliminadno el prefijo "Bearer "
const token = authHeader.split(" ")[1];
// Validación de token autorizado proporcionado por el cliente
if (token === process.env.DEFAULT_TOKEN)
return next();
try {
// Verifica el token de Firebase usando firebase-admin
const decodedToken = await admin.auth().verifyIdToken(token);
req.user = decodedToken; // Añade el usuario decodificado a la solicitud
next();
}
catch (error) {
console.log("Error verifying Firebase ID token:", error);
return res.status(401).json({ message: "Unauthorized", error });
}
}
41 changes: 41 additions & 0 deletions server/dist/playwright.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { defineConfig, devices } from "@playwright/test";
import dotenv from "dotenv";
dotenv.config();
export default defineConfig({
// Look for test files in the "tests" directory, relative to this configuration file.
testDir: "dist/tests",
// Run all tests in parallel.
fullyParallel: true,
// Fail the build on CI if you accidentally left test.only in the source code.
forbidOnly: !!process.env.CI,
// Retry on CI only.
retries: process.env.CI ? 2 : 0,
// Opt out of parallel tests on CI.
workers: process.env.CI ? 1 : undefined,
// Reporter to use
reporter: "html",
use: {
// Base URL to use in actions like `await page.goto('/')`.
baseURL: "http://127.0.0.1:8080",
// Collect trace when retrying the failed test.
trace: "on-first-retry",
// Add extra HTTP headers
extraHTTPHeaders: {
Authorization: `Bearer ${process.env.DEFAULT_TOKEN}`,
Aplication: "aplication-json",
},
},
// Configure projects for major browsers.
projects: [
{
name: "chromium",
use: { ...devices["Desktop Chrome"] },
},
],
// Run your local dev server before starting the tests.
webServer: {
command: "npm run start",
url: "http://127.0.0.1:8080",
reuseExistingServer: !process.env.CI,
},
});
Loading

0 comments on commit 6d81ae8

Please sign in to comment.