本文整理汇总了TypeScript中koa.Context类的典型用法代码示例。如果您正苦于以下问题:TypeScript Context类的具体用法?TypeScript Context怎么用?TypeScript Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: async
export default async (ctx: Context, next: Function) => {
const header = 'X-Experience-API-Version';
if (ctx.get(header) && ctx.get(header).substring(0, 3) === config.xApiVersion.substring(0, 3)) {
await next();
} else {
ctx.body = "Invalid 'X-Experience-API-Version' header was supplied";
ctx.status = 400;
}
ctx.set(header, config.xApiVersion);
};
示例2: async
export default async (ctx: Context, next: () => Promise<any>) => {
try {
await next();
if (ctx.response.status === 404 && !ctx.response.body) {
ctx.throw(404);
}
} catch (err) {
ctx.status = typeof err.status === 'number' ? err.status : 500;
// (<any> ctx.app).emit('error', err, ctx);
const type = ctx.accepts(['json', 'html', 'text/plain']);
// json
if (type === 'json') {
ctx.type = 'application/json';
if (process.env.NODE_ENV !== 'production') {
ctx.body = { code: ctx.status, error: err.message, stack: err.stack };
}
else if (err.expose) {
ctx.body = { code: ctx.status, error: err.message };
}
else {
ctx.body = { code: ctx.status, error: STATUS_CODES[ctx.status] };
}
}
// html
else if (type === 'html') {
ctx.type = 'text/html';
ctx.body = ctx.render('../templates/error.html', {
error: err,
status: ctx.status,
env: process.env.NODE_ENV,
});
}
// any
else {
ctx.type = 'text/plain';
if (process.env.NODE_ENV !== 'production') {
ctx.body = err.message;
}
else if (err.expose) {
ctx.body = err.message;
}
else {
ctx.body = STATUS_CODES[ctx.status];
}
}
// 错误日志
logger.error(`path: ${ctx.path}, status: ${err.status}, message: ${err.message}, stack: ${err.stack}`);
}
};
示例3: default
export default (ctx: Context, next: () => Promise<any>) => {
if ('/favicon.ico' !== ctx.path) {
return next();
}
if ('GET' !== ctx.method && 'HEAD' !== ctx.method) {
ctx.set('Allow', 'GET, HEAD, OPTIONS');
ctx.status = ctx.method === 'OPTIONS' ? 200 : 405;
}
else {
ctx.set('Cache-Control', CACHE);
ctx.type = 'image/x-icon';
ctx.body = ICON;
}
};
示例4: async
export default async (ctx: Context, next: Function) => {
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
ctx.set(
'Access-Control-Allow-Headers',
// tslint:disable-next-line:max-line-length
'X-Experience-API-Version,X-Access-Token,X-Id-Token,X-Entity-Id,X-Entity-Type,Accept,Authorization,Content-Type,If-Match,If-None-Match,Cache-Control,Pragma,Expires'
);
if (ctx.method === 'OPTIONS') {
ctx.status = 200;
} else {
await next();
}
};
示例5: next
router.param('book', (book: string, ctx: Context, next: () => Promise<any>) => {
if (isNumber(book)) {
const bookNumber = parseInt(book, 10)
if (bookNumber < 0 || bookNumber > books.get('rev')!!) {
ctx.throw('Book out of bounds', 422)
}
ctx.params.book_id = bookNumber
} else {
book = book.toLowerCase()
if (!books[book]) {
ctx.throw('Unknown book', 422)
}
ctx.params.book_id = books[book]
}
return next()
})
示例6: redirect
function redirect(ctx: Context, url: string, params: any): void {
const str: string[] = []
for (let item in params) {
str.push(`${item}=${item === 'redirect_uri' ? encodeURIComponent(params[item]): params[item]}`)
}
ctx.redirect(`${url}?${str.join('&')}`)
}
示例7: async
router.get('/authorize', async (ctx: Context): Promise<void> => {
try {
const query = ctx.query, req = new Request(ctx.request), res = new Response(ctx.response)
const code = await oauth.authorize(req, res)
ctx.redirect(`${query.redirect_uri}?code=${code}state=${query.state}`)
} catch (err) {
console.log(err)
}
})
示例8: async
export default async (ctx: Context, next: Function) => {
const apiKey = ctx.get('X-API-Key');
if (apiKey === config.appApiKey) {
await next();
} else {
ctx.body = "Access denied. Invalid 'X-API-Key' header was supplied";
ctx.status = 403;
}
};
示例9: async
return async (ctx: Context, next) => {
const startTime = new Date().getTime();
const date = new Date().toISOString();
await next();
const responseTime = new Date().getTime() - startTime;
logger.info({
date,
status: ctx.status,
remoteAddress: ctx.ip,
method: ctx.method,
url: ctx.url,
referrer: ctx.get('Referrer'),
userAgent: ctx.get('user-agent'),
responseTime,
});
};
示例10: async
const render = async (
ctx: Context,
template: string,
cards?: any[],
data?: any
) => {
const locals = await buildRenderParams(ctx.user, cards, data);
log.debug(`rendering ${template}`, locals);
await ctx.render(template, locals);
};