Skip to content

Instantly share code, notes, and snippets.

@SaraVieira
Created July 5, 2022 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SaraVieira/8cdb29104016ad5b9a164b19cf96e25e to your computer and use it in GitHub Desktop.
Save SaraVieira/8cdb29104016ad5b9a164b19cf96e25e to your computer and use it in GitHub Desktop.
import nextConnect from "next-connect";
import aws from "aws-sdk";
import multer from "multer";
import multerS3 from "multer-s3-v3";
import { getVideoTypeByEnv } from "@/src/utils/video-type";
import { UPLOAD_TYPE } from "@/src/constants/lessons";
import { adminOnlyAPIRoute } from "@/src/utils/session";
import { ERROR_MESSAGES } from "@/src/constants/errors";
const uploadType = getVideoTypeByEnv();
let upload;
if (UPLOAD_TYPE.S3 === uploadType || uploadType === UPLOAD_TYPE.S3_COMPATIBLE) {
const {
S3_BUCKET,
S3_ACCESSKEYID,
S3_SECRETACCESSKEY,
S3_REGION,
S3_ENDPOINT,
S3_ACL,
} = process.env;
const common = {
accessKeyId: S3_ACCESSKEYID,
secretAccessKey: S3_SECRETACCESSKEY,
region: S3_REGION,
};
var s3 = new aws.S3(
S3_ENDPOINT
? { endpoint: new aws.Endpoint(S3_ENDPOINT), ...common }
: common
);
upload = multer({
storage: multerS3({
s3: s3,
acl: S3_ACL || "public-read",
bucket: S3_BUCKET,
metadata: (req, file, cb) => cb(null, { fieldName: file.fieldname }),
key: (_request, file, cb) => cb(null, file.originalname),
throwMimeTypeConflictErrorIf: (contentType, mimeType) =>
![mimeType, "application/octet-stream"].includes(contentType),
}),
});
}
if (UPLOAD_TYPE.SERVER_UPLOAD === uploadType) {
upload = multer({
storage: multer.diskStorage({
destination: process.env.UPLOAD_PATH,
filename: (req, file, cb) => cb(null, file.originalname),
}),
});
}
const apiRoute = nextConnect({
onError(error, req, res) {
res.status(501).json({ error: ERROR_MESSAGES.UPLOAD_VIDEO_ERROR });
},
onNoMatch(req, res) {
res.status(405).json({ error: ERROR_MESSAGES.METHOD_NOT_ALLOWED });
},
});
if (upload) {
apiRoute.use(upload.single("video"));
apiRoute.post(async (req, res) => {
adminOnlyAPIRoute(req, res);
const path =
req.file.location || process.env.NEXT_PUBLIC_URL + "/" + req.file.path;
res.status(200).json({ path });
});
} else {
apiRoute.post(async (req, res) => {
res.status(501).json({ error: "You have nothing set up for uploads" });
});
}
export default apiRoute;
export const config = {
api: {
bodyParser: false,
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment