ストリーム経由でAPIにリクエストできるように

This commit is contained in:
syuilo
2018-04-11 17:40:01 +09:00
parent 91791834be
commit bd3d57a67f
15 changed files with 137 additions and 179 deletions

View File

@@ -2,55 +2,33 @@ import * as express from 'express';
import { Endpoint } from './endpoints';
import authenticate from './authenticate';
import { IAuthContext } from './authenticate';
import _reply from './reply';
import limitter from './limitter';
import call from './call';
import { IUser } from '../../models/user';
import { IApp } from '../../models/app';
export default async (endpoint: Endpoint, req: express.Request, res: express.Response) => {
const reply = _reply.bind(null, res);
let ctx: IAuthContext;
const reply = (x?: any, y?: any) => {
if (x === undefined) {
res.sendStatus(204);
} else if (typeof x === 'number') {
res.status(x).send({
error: x === 500 ? 'INTERNAL_ERROR' : y
});
} else {
res.send(x);
}
};
let user: IUser;
let app: IApp;
// Authentication
try {
ctx = await authenticate(req);
[user, app] = await authenticate(req.body['i']);
} catch (e) {
return reply(403, 'AUTHENTICATION_FAILED');
}
if (endpoint.secure && !ctx.isSecure) {
return reply(403, 'ACCESS_DENIED');
}
if (endpoint.withCredential && ctx.user == null) {
return reply(401, 'PLZ_SIGNIN');
}
if (ctx.app && endpoint.kind) {
if (!ctx.app.permission.some(p => p === endpoint.kind)) {
return reply(403, 'ACCESS_DENIED');
}
}
if (endpoint.withCredential && endpoint.limit) {
try {
await limitter(endpoint, ctx); // Rate limit
} catch (e) {
// drop request if limit exceeded
return reply(429);
}
}
let exec = require(`${__dirname}/endpoints/${endpoint.name}`);
if (endpoint.withFile) {
exec = exec.bind(null, req.file);
}
// API invoking
try {
const res = await exec(req.body, ctx.user, ctx.app, ctx.isSecure);
reply(res);
} catch (e) {
reply(400, e);
}
call(endpoint, user, app, req.body, req).then(reply).catch(e => reply(400, e));
};