This commit is contained in:
oitsjustjose 2022-04-16 17:41:12 -05:00
commit 88a7e70ead
11 changed files with 135 additions and 112 deletions

View file

@ -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;
};

View file

@ -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;

View file

@ -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);
};

View file

@ -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 });
};

View file

@ -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;

View file

@ -1,9 +0,0 @@
import { Document, model, Schema } from "mongoose";
export type FileModel = Document & { key: string };
const FileSchema = new Schema<FileModel>({
key: { type: String, required: true },
});
export default model<FileModel>("files", FileSchema, "files");

View file

@ -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;
};

View file

@ -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");
};

View file

@ -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;