yumechi-no-kuni/src/server/api/get-params.ts

30 lines
667 B
TypeScript
Raw Normal View History

2018-07-05 09:36:07 -05:00
import { Context } from 'cafy';
2018-07-05 08:35:35 -05:00
type Defs = {
2018-07-05 09:36:07 -05:00
params: { [key: string]: Context<any> }
2018-07-05 08:35:35 -05:00
};
export default function <T extends Defs>(defs: T, params: any): [{
2018-07-05 09:36:07 -05:00
[P in keyof T['params']]: ReturnType<T['params'][P]['get']>[0];
2018-07-05 08:35:35 -05:00
}, Error] {
const x: any = {};
let err: Error = null;
Object.keys(defs.params).some(k => {
2018-07-05 09:36:07 -05:00
const [v, e] = defs.params[k].get(params[k]);
2018-07-05 08:35:35 -05:00
if (e) {
2018-10-26 00:38:34 -05:00
err = new Error(e.message);
err.name = 'INVALID_PARAM';
(err as any).param = k;
2018-07-05 08:35:35 -05:00
return true;
} else {
2018-07-05 09:36:07 -05:00
if (v === undefined && defs.params[k].data.default) {
x[k] = defs.params[k].data.default;
2018-07-05 08:35:35 -05:00
} else {
x[k] = v;
}
return false;
}
});
return [x, err];
}