From 88a7e70eadefde595a2010b83a3df7f59f051a55 Mon Sep 17 00:00:00 2001 From: oitsjustjose Date: Sat, 16 Apr 2022 17:41:12 -0500 Subject: [PATCH] Cleanup --- backend/.envrc | 18 +++++ backend/package.json | 1 - backend/src/app.ts | 75 +++++++++------------ backend/src/app/controllers/index.ts | 3 + backend/src/app/controllers/s3/crud/get.ts | 16 +++++ backend/src/app/controllers/s3/crud/post.ts | 8 +++ backend/src/app/controllers/s3/index.ts | 36 ++++++++++ backend/src/app/models/S3FileLink.ts | 9 --- backend/src/app/util/S3.ts | 20 ++++++ backend/src/multer.ts | 54 --------------- backend/src/server.ts | 3 +- 11 files changed, 133 insertions(+), 110 deletions(-) create mode 100644 backend/.envrc create mode 100644 backend/src/app/controllers/s3/crud/get.ts create mode 100644 backend/src/app/controllers/s3/crud/post.ts create mode 100644 backend/src/app/controllers/s3/index.ts delete mode 100644 backend/src/app/models/S3FileLink.ts create mode 100644 backend/src/app/util/S3.ts delete mode 100644 backend/src/multer.ts diff --git a/backend/.envrc b/backend/.envrc new file mode 100644 index 0000000..a617b5b --- /dev/null +++ b/backend/.envrc @@ -0,0 +1,18 @@ +export APP_NAME='OpenCommerce Dev' +export LOGO="https://pbs.twimg.com/profile_images/1347273728141500418/mClA3m5v_400x400.png" +export URL=localhost:3000 + +export MONGO_URI=localhost +export MONGO_COLLECTION=OpenCommerce + +export JWT_SECRET=asdf + +export URL=localhost:5000 + +export NODEMAILER_ADDRESS=keycloak@forgeserv.net +export NODEMAILER_PASSWORD=crah.spur4vaf.HOUD + +export AWS_REGION=us-east-2 +export AWS_BUCKET=jstovall-opencommerce-dev +export AWS_ACCESS_KEY_ID=AKIAT6IFHPMGHY3TOAAG +export AWS_SECRET_ACCESS_KEY=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 diff --git a/backend/package.json b/backend/package.json index 6196073..51ca1bb 100644 --- a/backend/package.json +++ b/backend/package.json @@ -25,7 +25,6 @@ "aws-sdk": "^2.1116.0", "body-parser": "^1.19.0", "cors": "^2.8.5", - "dotenv": "^16.0.0", "email-validator": "^2.0.4", "express": "^4.17.1", "jsonwebtoken": "^8.5.1", diff --git a/backend/src/app.ts b/backend/src/app.ts index 8080fed..d9e96e8 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -1,15 +1,10 @@ -import { config as LoadDotenv } from "dotenv"; - import { json, urlencoded } from "body-parser"; import cors from "cors"; import express from "express"; -import winston from "winston"; import Routes from "./app/controllers"; import AccessLog from "./app/middleware/AccessLog"; import UserInjection from "./app/middleware/UserInjection"; import { UserModel } from "./app/models/User"; -import { LOGGER } from "./app/util/Logger"; -import Multify from "./multer"; interface AuthenticatableRequest { user?: UserModel; @@ -21,46 +16,36 @@ declare global { } } -if (process.env.NODE_ENV !== "production") { - LoadDotenv(); - LOGGER.add( - new winston.transports.Console({ - format: winston.format.simple(), - }) - ); -} +export default () => { + const app = express(); -const app = express(); + app.use(cors()); + app.use(json()); + app.use(urlencoded({ extended: true })); + app.use(UserInjection()); + app.use(AccessLog()); -app.use(cors()); -app.use(json()); -app.use(urlencoded({ extended: true })); -app.use(UserInjection()); -app.use(AccessLog()); - -console.log("-------------------------------------------------"); -Multify(app); -Routes.forEach(({ path, httpMethod, handler }) => { - switch (httpMethod) { - case "GET": - app.get(path, handler); - break; - case "POST": - app.post(path, handler); - break; - case "DELETE": - app.delete(path, handler); - break; - case "PUT": - app.put(path, handler); - break; - case "PATCH": - app.patch(path, handler); - break; - } + Routes.forEach(({ path, httpMethod, middleware, handler }) => { + switch (httpMethod) { + case "GET": + app.get(path, ...(middleware || []), handler); + break; + case "POST": + app.post(path, ...(middleware || []), handler); + break; + case "DELETE": + app.delete(path, ...(middleware || []), handler); + break; + case "PUT": + app.put(path, ...(middleware || []), handler); + break; + case "PATCH": + app.patch(path, ...(middleware || []), handler); + break; + } + console.log("-------------------------------------------------"); + console.log(`${httpMethod}: ${path}`); + }); console.log("-------------------------------------------------"); - console.log(`${httpMethod}: ${path}`); -}); -console.log("-------------------------------------------------"); - -export default app; + return app; +}; diff --git a/backend/src/app/controllers/index.ts b/backend/src/app/controllers/index.ts index 448b3a9..5b96e50 100644 --- a/backend/src/app/controllers/index.ts +++ b/backend/src/app/controllers/index.ts @@ -2,17 +2,20 @@ import { Request, Response } from "express"; import ProductRoutes from "./product"; import ReviewRoutes from "./review"; import UserRoutes from "./user"; +import S3Routes from "./s3"; export type RouteCollection = { httpMethod: "GET" | "POST" | "DELETE" | "PUT" | "PATCH"; path: string; handler: (arg1: Request, arg2: Response) => any; + middleware?: any[]; }; const routes: RouteCollection[] = [ ...ProductRoutes, ...UserRoutes, ...ReviewRoutes, + ...S3Routes, ]; export default routes; diff --git a/backend/src/app/controllers/s3/crud/get.ts b/backend/src/app/controllers/s3/crud/get.ts new file mode 100644 index 0000000..fbedcdf --- /dev/null +++ b/backend/src/app/controllers/s3/crud/get.ts @@ -0,0 +1,16 @@ +import { Request, Response } from "express"; +import getS3Instace from "../../../util/S3"; + +export default async (req: Request, res: Response) => { + if (!req.params.key) { + return res.status(404).send(); + } + + const signedUrl = await getS3Instace().getSignedUrlPromise("getObject", { + Bucket: process.env.AWS_BUCKET, + Key: req.params.key, + Expires: 604800, + }); + + return res.redirect(signedUrl); +}; diff --git a/backend/src/app/controllers/s3/crud/post.ts b/backend/src/app/controllers/s3/crud/post.ts new file mode 100644 index 0000000..5e864b2 --- /dev/null +++ b/backend/src/app/controllers/s3/crud/post.ts @@ -0,0 +1,8 @@ +import { Request, Response } from "express"; +import S3FileLink from "../../../models/S3FileLink"; + +export default async (req: Request, res: Response) => { + // const f = new S3FileLink({ key: (req.file as any).key }); + // await f.save(); + return res.status(200).json({ output: (req.file as any).key }); +}; diff --git a/backend/src/app/controllers/s3/index.ts b/backend/src/app/controllers/s3/index.ts new file mode 100644 index 0000000..5c74d73 --- /dev/null +++ b/backend/src/app/controllers/s3/index.ts @@ -0,0 +1,36 @@ +import { RouteCollection } from ".."; +import post from "./crud/post"; +import get from "./crud/get"; +import moment from "moment"; +import multer from "multer"; +import multerS3 from "multer-s3"; +import getS3Instace from "../../util/S3"; + +const uploader = multer({ + storage: multerS3({ + s3: getS3Instace(), + bucket: process.env.AWS_BUCKET, + key: function (req, file, cb) { + cb(null, `${moment().toISOString()}-${file.originalname}`); + }, + metadata: function (req, file, cb) { + cb(null, { fieldName: file.fieldname }); + }, + }), +}); + +const routes: RouteCollection[] = [ + { + httpMethod: "GET", + path: "/api/v1/fileupload/:key", + handler: get, + }, + { + httpMethod: "POST", + path: "/api/v1/fileupload", + handler: post, + middleware: [uploader.single("file")], + }, +]; + +export default routes; diff --git a/backend/src/app/models/S3FileLink.ts b/backend/src/app/models/S3FileLink.ts deleted file mode 100644 index d586b03..0000000 --- a/backend/src/app/models/S3FileLink.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Document, model, Schema } from "mongoose"; - -export type FileModel = Document & { key: string }; - -const FileSchema = new Schema({ - key: { type: String, required: true }, -}); - -export default model("files", FileSchema, "files"); diff --git a/backend/src/app/util/S3.ts b/backend/src/app/util/S3.ts new file mode 100644 index 0000000..aebd8cf --- /dev/null +++ b/backend/src/app/util/S3.ts @@ -0,0 +1,20 @@ +import aws from "aws-sdk"; + +let cached: aws.S3 | null = null; + +export default () => { + if (cached) { + return cached; + } + + const S3 = new aws.S3({ + region: process.env.AWS_REGION, + accessKeyId: process.env.AWS_ACCESS_KEY_ID, + secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, + apiVersion: "2006-03-01", + signatureVersion: "v4", + }); + + cached = S3; + return cached; +}; diff --git a/backend/src/multer.ts b/backend/src/multer.ts deleted file mode 100644 index 2ba51e2..0000000 --- a/backend/src/multer.ts +++ /dev/null @@ -1,54 +0,0 @@ -import aws from "aws-sdk"; -import { Express } from "express"; -import moment from "moment"; -import multer from "multer"; -import multers3 from "multer-s3"; -import S3FileLink from "./app/models/S3FileLink"; - -export default (app: Express) => { - const s3 = new aws.S3({ - region: process.env.AWS_REGION, - accessKeyId: process.env.AWS_ACCESS_KEY_ID, - secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, - apiVersion: "2006-03-01", - signatureVersion: "v4", - }); - - const uploader = multer({ - storage: multers3({ - s3, - bucket: process.env.AWS_BUCKET, - key: function (req, file, cb) { - cb(null, `${moment().toISOString()}-${file.originalname}`); - }, - metadata: function (req, file, cb) { - cb(null, { fieldName: file.fieldname }); - }, - }), - }); - - // Special endpoint for the image upload - app.post("/api/v1/fileupload", uploader.single("file"), async (req, res) => { - const f = new S3FileLink({ key: (req.file as any).key }); - await f.save(); - return res.status(200).json({ output: f.key }); - }); - - app.get("/api/v1/fileupload/:key", async (req, res) => { - if (!req.params.key) { - return res.status(404).send(); - } - - const signedUrl = await s3.getSignedUrlPromise("getObject", { - Bucket: process.env.AWS_BUCKET, - Key: req.params.key, - Expires: 604800, - }); - - return res.redirect(signedUrl); - }); - - console.log("GET /api/v1/fileupload/:key"); - console.log("-------------------------------------------------"); - console.log("POST /api/v1/fileupload"); -}; diff --git a/backend/src/server.ts b/backend/src/server.ts index 166dd47..ba55f6c 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -1,7 +1,8 @@ -import app from "./app"; +import BuildApp from "./app"; import { LOGGER } from "./app/util/Logger"; import ConnectDb from "./db"; +const app = BuildApp(); ConnectDb(); const port = process.env.PORT || 3000;