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

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