koa#Next TypeScript Examples
The following examples show how to use
koa#Next.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: authMiddleware.ts From bluebubbles-server with Apache License 2.0 | 6 votes |
AuthMiddleware = async (ctx: Context, next: Next) => {
const params = ctx.request.query;
// Make sure we have a token
const token = (params?.guid ?? params?.password ?? params?.token) as string;
if (!token) throw new Unauthorized({ error: "Missing server password!" });
// Make sure we have a password from the database
const password = String(Server().repo.getConfig("password") as string);
if (!password) {
throw new ServerError({ error: "Failed to retrieve password from the database" });
}
// Validate the passwords match
if (safeTrim(password) !== safeTrim(token)) throw new Unauthorized();
// Go to the next middleware
await next();
}
Example #2
Source File: comments.ts From Corsace with MIT License | 6 votes |
async function canComment (ctx: ParameterizedContext, next: Next): Promise<any> {
if (!ctx.state.user.canComment) {
return ctx.body = {
error: "You cannot comment",
};
}
await next();
}
Example #3
Source File: authCheck.ts From insmemo with GNU General Public License v3.0 | 6 votes |
export async function validSigninCookie(ctx: Context, next: Next) {
const userId = ctx.session?.userId ?? "";
if (!Boolean(userId)) {
throw new Error("20001");
}
await next();
}
Example #4
Source File: Router.ts From uni-cloud-router with Apache License 2.0 | 6 votes |
private wrapMiddleware(
fn: Middleware<StateT, CustomT>,
options?: MiddlewareOptions
) {
const matchFn = createRouteMatch(options)
const mw = (ctx: ParameterizedContext<StateT, CustomT>, next: Next) => {
if (!matchFn(ctx)) {
return next()
}
return fn(ctx, next)
}
if (options && options.name) {
mw._name = options.name
}
if (!mw._name) {
mw._name = (fn as any)._name || fn.name
}
return mw
}
Example #5
Source File: ApiLogger.ts From l2beat with MIT License | 6 votes |
export function createApiLogger(logger: Logger) {
return async function (ctx: Context, next: Next) {
const key = Symbol.for('request-received.startTime')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const start: number = ctx[key as any]?.getTime?.() ?? Date.now()
logger.info({ type: 'request', method: ctx.method, url: ctx.originalUrl })
try {
await next()
} catch (error) {
logger.error(error)
throw error
}
const { res } = ctx
const done = () => {
res.removeListener('finish', done)
res.removeListener('close', done)
const timeMs = Date.now() - start
logger.info({
type: 'response',
status: ctx.status,
timeMs,
method: ctx.method,
url: ctx.originalUrl,
})
}
res.once('finish', done)
res.once('close', done)
}
}
Example #6
Source File: error.ts From tezos-academy with MIT License | 6 votes |
error = () => async (ctx: Context, next: Next): Promise<void> => {
try {
await next()
} catch (err) {
console.error(err)
ctx.status = err.statusCode || err.status || 500
ctx.body = {
error: err.message,
}
// ctx.app.emit('error', err, ctx);
}
}
Example #7
Source File: index.ts From electron with MIT License | 6 votes |
export async function AllHello(ctx: Context, next: Next) {
if (ctx.method === 'POST') {
await Send(ctx).succ(ctx.request.body);
return;
}
if (ctx.method === 'GET') {
await Send(ctx).succ(ctx.request.query);
return;
}
await Send(ctx).succ(ctx.querystring);
}
Example #8
Source File: metricsMiddleware.ts From bluebubbles-server with Apache License 2.0 | 5 votes |
MetricsMiddleware = async (ctx: Context, next: Next) => {
const now = new Date().getTime();
await next();
const later = new Date().getTime();
Server().log(`Request to ${ctx?.request?.path?.toString() ?? "N/A"} took ${later - now} ms`);
}
Example #9
Source File: middleware.ts From Corsace with MIT License | 5 votes |
export async function redirectToMainDomain (ctx: ParameterizedContext, next: Next): Promise<void> {
// Redirect to the main host (where user gets redirected post-oauth) to apply redirect cookie on the right domain
if(ctx.host !== mainHost) {
ctx.redirect(`${config[process.env.NODE_ENV === "production" ? "corsace" : "api"].publicUrl}${ctx.originalUrl}`);
return;
}
await next();
}