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 f8de5e9
Show file tree
Hide file tree
Showing 38 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
2 changes: 1 addition & 1 deletion server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,6 @@ async function inicializeApp() {
}
}

inicializeApp().catch((error) => {
export default inicializeApp().catch((error) => {
console.error("Error starting the server:", error);
});
2 changes: 1 addition & 1 deletion server/lib/resend/resend.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import dotenv from "dotenv";
dotenv.config();
////////////////////////////////////////////////////////////////
import { Message, NoteType, SubscriberType } from "types/types";
import { NoteType, SubscriberType } from "types/types";
import { Resend } from "resend";

// Configurar el cliente de Mandrill
Expand Down
25 changes: 0 additions & 25 deletions server/package-lock.json

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

4 changes: 2 additions & 2 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"type": "module",
"main": "index.ts",
"scripts": {
"start": "npm run build && node dist/index.js",
"dev": "node --loader ts-node/esm src/index.js",
"start": "node public/index.js",
"dev": "node --loader ts-node/esm index.js",
"test": "npm run build && playwright test",
"build": "tsc"
},
Expand Down
114 changes: 114 additions & 0 deletions server/public/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import dotenv from "dotenv";
dotenv.config();
///////////////////////////////////////////
import { connectDB } from "./src/mongodb/mongodb.js";
import express from "express";
import cors from "cors";
import { router } from "./routes/routes.js";
import net from "net";
// Extendemos el límite para que pueda almacenar imagenes en base64
async function inicializeApp() {
const app = express();
// Origenes permitidos
const allowedOrigins = ["https://thefluentspanishhouse.com", "http://localhost:5173", process.env.URL_WEB_TEST];
// Configuración global de CORS
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
}
else {
callback(new Error("Not allowed by CORS"));
}
},
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true,
}));
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ limit: "10mb", extended: true }));
app.use(express.json());
app.use(express.text());
// Conexión a la base de datos
try {
await connectDB();
}
catch (error) {
throw new Error("Error connecting to the database");
}
// Enpoint de bienvenida
app.get("/", (req, res) => {
res.send("Welcome to thefluentespnaishouse server");
});
// Rutas de la aplicación
app.use(router);
// Obtener la URL de los preview para hacer testing
app.get("/api/test", async (_req, res) => {
try {
const previewUrl = process.env.VERCEL_URL;
if (!previewUrl)
throw new Error("VERCEL_URL no está definida");
res.send(previewUrl);
}
catch (error) {
res.status(500).json({ error: "Error en el servidor para obtener URL de preview" });
}
});
// Si es development y preview asignamos el puerto disponible a partir de 8080
if (process.env.NODE_ENV !== "production") {
const PORT_BACKEND = 8080;
// Creamos una funcion flecha que devuelbe una promesa
const checkPort = (port) => {
return new Promise((resolve, reject) => {
// Creamos un servidor con net nativo de (NodeJS)
const server = net.createServer();
// Intentar escuchar en el puerto
server.listen(port);
// Verificamos si el puerto esta en uso si lo esta devuleve false, si ocurre un error lo rechaza
server.once("error", (err) => {
if (err.code === "EADDRINUSE") {
resolve(false);
}
else {
reject(err);
}
});
// Si el puerto esta libre lo cerramos y resolvemos la promesa
server.once("listening", () => {
server.close();
resolve(true);
});
});
};
const startServer = async (port) => {
// Encontramos un puerto libre de [8080, 8090]
if (port > 8090) {
console.log("No ports available");
return;
}
// Encontra un puerto libre y se lo asigna al servidor, si no encuentra uno libre lo asigna al siguiente
const isPortFree = await checkPort(port);
if (isPortFree) {
app.listen(port, () => {
console.log(`Server running: http://localhost:${port}`);
});
}
else {
console.log(`Port ${port} is in use, please choose another port.`);
startServer(port + 1);
}
};
startServer(PORT_BACKEND).catch((error) => {
console.error("Error starting the server:", error);
});
}
else {
const PORT_BACKEND = 8080;
app.listen(PORT_BACKEND, () => {
console.log(`Server runing: http://localhost:${PORT_BACKEND}`);
});
}
}
export default inicializeApp().catch((error) => {
console.error("Error starting the server:", error);
});
41 changes: 41 additions & 0 deletions server/public/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/public/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;
}
};
Loading

0 comments on commit f8de5e9

Please sign in to comment.