Upload Service
Course: Code along - Vercel - chapter 1
Install Node.js
Official Page - https://nodejs.org/en/download Good resource to follow along - https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-20-04
Initialise an empty typescript project
mkdir vercelcd vercelnpm init -ynpx tsc --initBasic typescript configuration
- Change
rootDirtosrc - Change
outDirtodistfor the pro
Add `express` , `redis` , `aws-sdk` , `simple-git` , `cors` as dependencies
npm install express @types/express redis aws-sdk simple-git corsInitialize a simple express app in `index.ts` listening on port `3000`
Initialise an endpoint that the user will hit and send the `repo url` as input
import express from "express";import cors from "cors";import { generate } from "./utils";
const app = express();app.use(cors())app.use(express.json());
// POSTMANapp.post("/deploy", async (req, res) => { const repoUrl = req.body.repoUrl;});
app.listen(3000);Create a function that randomly generates an id for this session. Call it `generate`
function generate() { const subset = "123456789qwertyuiopasdfghjklzxcvbnm"; const length = 5; const id = ""; for (let i = 0; i < length; i++) { id += subset[Math.floor(Math.random() * subset.length)]; } return id;}Use `simple-git` to clone the repo into a new folder (`/out/id` ).
import express from "express";import cors from "cors";import simpleGit from "simple-git";import { generate } from "./utils";
const app = express();app.use(cors())app.use(express.json());
// POSTMANapp.post("/deploy", async (req, res) => { const repoUrl = req.body.repoUrl; const id = generate(); // asd12 await simpleGit().clone(repoUrl, `output/${id}`);
res.json({ id: id })});
app.listen(3000);Write a function that gets the `paths` of all the files in the `/out/id` folder
import fs from "fs";import path from "path";
export const getAllFiles = (folderPath: string) => { let response: string[] = [];
const allFilesAndFolders = fs.readdirSync(folderPath);allFilesAndFolders.forEach(file => { const fullFilePath = path.join(folderPath, file); if (fs.statSync(fullFilePath).isDirectory()) { response = response.concat(getAllFiles(fullFilePath)) } else { response.push(fullFilePath); } }); return response;}Write a function that uploads a file given a `path` to S3
import { S3 } from "aws-sdk";import fs from "fs";
// replace with your own credentialsconst s3 = new S3({ accessKeyId: "7ea9c3f8c7f0f26f0d21c5ce99d1ad6a", secretAccessKey: "b4df203781dd711223ce931a2d7ca269cdbf81bb530de4548474584951b798be", endpoint: "https://e21220f4758c0870ba9c388712d42ef2.r2.cloudflarestorage.com"})
// fileName => output/12312/src/App.jsx// filePath => /Users/harkiratsingh/vercel/dist/output/12312/src/App.jsxexport const uploadFile = async (fileName: string, localFilePath: string) => { const fileContent = fs.readFileSync(localFilePath); const response = await s3.upload({ Body: fileContent, Bucket: "vercel", Key: fileName, }).promise(); console.log(response);}Iterate over all the files and upload them to S3 one by one (or together)
const files = getAllFiles(path.join(__dirname, `output/${id}`));
files.forEach(async file => { await uploadFile(file.slice(__dirname.length + 1), file);})Start redis locally
Initialize a redis publisher
import { createClient } from "redis";const publisher = createClient();publisher.connect();Use `redis queues` to push the `uploadId` in the queue
publisher.lPush("build-queue", id);Also store the current video id’s status as `uploaded` .
publisher.hSet("status", id, "uploaded");Expose a `status` endpoint that the frontend will poll to get back the `status` of a video. It needs to check redis for the current value.
app.get("/status", async (req, res) => { const id = req.query.id; const response = await subscriber.hGet("status", id as string); res.json({ status: response })})