2018-11-01 23:47:44 -05:00
|
|
|
import * as fs from 'fs';
|
|
|
|
import { ILocalUser } from '../../models/user';
|
|
|
|
import { IApp } from '../../models/app';
|
|
|
|
import { IEndpointMeta } from './endpoints';
|
2019-02-21 20:46:58 -06:00
|
|
|
import { ApiError } from './error';
|
2018-11-01 23:47:44 -05:00
|
|
|
|
|
|
|
type Params<T extends IEndpointMeta> = {
|
|
|
|
[P in keyof T['params']]: T['params'][P]['transform'] extends Function
|
|
|
|
? ReturnType<T['params'][P]['transform']>
|
|
|
|
: ReturnType<T['params'][P]['validator']['get']>[0];
|
|
|
|
};
|
|
|
|
|
2019-02-21 20:46:58 -06:00
|
|
|
export type Response = Record<string, any> | void;
|
|
|
|
|
|
|
|
export default function <T extends IEndpointMeta>(meta: T, cb: (params: Params<T>, user: ILocalUser, app: IApp, file?: any, cleanup?: Function) => Promise<Response>): (params: any, user: ILocalUser, app: IApp, file?: any) => Promise<any> {
|
2018-11-01 23:47:44 -05:00
|
|
|
return (params: any, user: ILocalUser, app: IApp, file?: any) => {
|
|
|
|
function cleanup() {
|
|
|
|
fs.unlink(file.path, () => {});
|
|
|
|
}
|
|
|
|
|
2019-02-21 20:46:58 -06:00
|
|
|
if (meta.requireFile && file == null) return Promise.reject(new ApiError({
|
|
|
|
message: 'File required.',
|
|
|
|
code: 'FILE_REQUIRED',
|
|
|
|
id: '4267801e-70d1-416a-b011-4ee502885d8b',
|
|
|
|
}));
|
2018-11-01 23:47:44 -05:00
|
|
|
|
|
|
|
const [ps, pserr] = getParams(meta, params);
|
|
|
|
if (pserr) {
|
|
|
|
if (file) cleanup();
|
|
|
|
return Promise.reject(pserr);
|
|
|
|
}
|
|
|
|
|
|
|
|
return cb(ps, user, app, file, cleanup);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2019-02-21 20:46:58 -06:00
|
|
|
function getParams<T extends IEndpointMeta>(defs: T, params: any): [Params<T>, ApiError] {
|
2018-11-04 06:11:54 -06:00
|
|
|
if (defs.params == null) return [params, null];
|
|
|
|
|
2018-11-01 23:47:44 -05:00
|
|
|
const x: any = {};
|
2019-02-21 20:46:58 -06:00
|
|
|
let err: ApiError = null;
|
2018-11-01 23:47:44 -05:00
|
|
|
Object.entries(defs.params).some(([k, def]) => {
|
|
|
|
const [v, e] = def.validator.get(params[k]);
|
|
|
|
if (e) {
|
2019-02-21 20:46:58 -06:00
|
|
|
err = new ApiError({
|
|
|
|
message: 'Invalid param.',
|
|
|
|
code: 'INVALID_PARAM',
|
|
|
|
id: '3d81ceae-475f-4600-b2a8-2bc116157532',
|
|
|
|
}, {
|
|
|
|
param: k,
|
|
|
|
reason: e.message
|
|
|
|
});
|
2018-11-01 23:47:44 -05:00
|
|
|
return true;
|
|
|
|
} else {
|
2018-11-04 08:13:35 -06:00
|
|
|
if (v === undefined && def.hasOwnProperty('default')) {
|
2018-11-01 23:47:44 -05:00
|
|
|
x[k] = def.default;
|
|
|
|
} else {
|
|
|
|
x[k] = v;
|
|
|
|
}
|
|
|
|
if (def.transform) x[k] = def.transform(x[k]);
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return [x, err];
|
|
|
|
}
|