Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const { join } = require('path')
const validate = require('express-validation')
const joiToJson = require('joi-to-json-schema')
const glob = require('glob-promise')
const imperium = require('imperium')
const { Router } = require('express')
const { flattenDeep } = require('lodash')
const { jwt } = require('./jwt')
const HttpError = require('./http-error')
const METHODS = ['get', 'post', 'put', 'delete', 'head', 'patch', 'all']
// Force allowUnkown as false
validate.options({
allowUnknownHeaders: true,
allowUnknownBody: false,
allowUnknownQuery: false,
allowUnknownParams: true,
allowUnknownCookies: true
})
module.exports = async function (srcDir, { conf, log, app }, hooks) {
let routes = []
let routeFiles = []
const { name, version, env } = conf
// Send back its name for discovery
app.get('/_', (req, res) => {
res.json({
name,
// enable CORS - Cross Origin Resource Sharing
app.use(cors());
// Serve any static files
app.use(express.static(path.join(__dirname, config.clientBuild)));
// mount all routes on /api/v1 path
app.use(API.ROOT, routes);
// Publish the frontend index.
app.use('/*', (req, res) => res.sendFile(path.join(__dirname, config.clientBuild, '/index.html')));
// Express could not sent array to Joi for validation
// https://github.com/AndrewKeig/express-validation/issues/36
expressValidation.options({
contextRequest: true,
});
// if error is not an instanceOf APIError, convert it.
app.use((err, req, res, next) => {
if (err instanceof expressValidation.ValidationError) {
// validation error contains errors which is an array of error each containing message[]
const unifiedErrorMessage = err.errors.map(error => error.messages.join('. ')).join(' and ');
const error = new APIError(unifiedErrorMessage, err.status, true);
return next(error);
}
if (!(err instanceof APIError)) {
const apiError = new APIError(err.message, err.status, err.isPublic);
return next(apiError);
}
return next(err);
// 获取静态文件
app.use('/avatar', express.static(staticConfig.upload.avatar.path));
app.use('/picture', express.static(staticConfig.upload.picture.path));
app.use(express.static(staticConfig.frontEnd.filePath));
// 处理请求
app.use('/api', router);
// TODO: file 需要单独鉴权
app.use('/uploads', express.static(
staticConfig.upload.file.path,
{ maxAge: staticConfig.upload.file.maxAge }
));
// 数据校验禁止附带多余字段
validation.options({
allowUnknownHeaders: false,
allowUnknownBody: false,
allowUnknownQuery: false,
allowUnknownParams: false,
allowUnknownCookies: false,
});
// 初始化 websocket
const server = utils.websocket.attachSocketIO(app).server;
let listenPromise = new Promise((resolve, reject) => {
server.listen(process.env.PORT || 8000, () => {
resolve();
utils.logger.writeInfoLog({ entity: 'Server', content: `API Service started on port ${process.env.PORT || 8000}` });
});
});