koa#Context TypeScript Examples
The following examples show how to use
koa#Context.
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: utils.ts From web with MIT License | 7 votes |
export function getRequestFilePath(contextOrString: Context | string, rootDir: string): string {
const url = typeof contextOrString === 'string' ? contextOrString : contextOrString.url;
const requestPath = getRequestBrowserPath(url);
if (isOutsideRootDir(requestPath)) {
const { normalizedPath, newRootDir } = resolvePathOutsideRootDir(requestPath, rootDir);
const filePath = toFilePath(normalizedPath);
return path.join(newRootDir, filePath);
} else {
const filePath = toFilePath(requestPath);
return path.join(rootDir, filePath);
}
}
Example #2
Source File: addProgress.spec.ts From tezos-academy with MIT License | 6 votes |
describe('User', () => {
beforeAll(async () => {
await mockConnect()
const created = await createTestUser('[email protected]', 'bob', 'Bob1234#')
user = created.user
jwt = created.jwt
next = created.next
})
it('can add progress', async (done) => {
const ctx: Context = {
request: {
headers: {
authorization: 'Bearer ' + jwt,
},
body: {
chapterDone: '/pascal/chapter-polymorphism',
},
},
} as Context
await addProgress(ctx, next)
expect(ctx.body.user).toBeDefined()
expect(ctx.body.user.progress).toContain('/pascal/chapter-polymorphism')
done()
})
afterAll(async () => {
await deleteTestUser(user._id)
})
})
Example #3
Source File: hexo.ts From hexon with GNU General Public License v3.0 | 6 votes |
router.delete("/page/:source", async (ctx: Context) => {
const hexo = container.resolve(HexoService)
const { source } = ctx.params
if (!source) {
ctx.status = 400
ctx.body = "need `source` "
return
}
ctx.body = await hexo.delete(source, "page")
})
Example #4
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 #5
Source File: index.ts From cli with MIT License | 6 votes |
export function useKoaDevPack(options: DevPackOptions) {
options.functionDir = options.functionDir || process.cwd();
const invokeFun = async () => {
return invokeByDev(options.dev);
};
return compose([
koaBodyParser({
enableTypes: ['form', 'json'],
}),
async (ctx: Context, next: () => Promise<any>) => {
const { createKoaGateway } = require('@midwayjs/gateway-common-http');
const gateway = createKoaGateway(options);
await gateway.transform(ctx, next, invokeFun);
},
]);
}
Example #6
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 #7
Source File: utils.ts From web with MIT License | 6 votes |
export function isInlineScriptRequest(contextOrUrl: Context | string) {
const url = typeof contextOrUrl === 'string' ? contextOrUrl : contextOrUrl.url;
return url.includes(`inline-script-`) && url.includes('source');
}
Example #8
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 #9
Source File: utils.ts From web with MIT License | 6 votes |
/**
* Returns the context body as string or buffer, depending on the content type.
* Response streams can only be read once, the response body is replaced with
* the stream result.
*/
export async function getResponseBody(ctx: Context): Promise<string | Buffer> {
let requestCanceled = false;
ctx.req.on('close', () => {
requestCanceled = true;
});
if (Buffer.isBuffer(ctx.body)) {
const contentLength = Number(ctx.response.get('content-length'));
const canStringify = !(await isBinaryFile(ctx.body, contentLength));
if (requestCanceled) {
throw new RequestCancelledError();
}
if (canStringify) {
ctx.body = ctx.body.toString();
}
return ctx.body as string;
}
if (typeof ctx.body === 'string') {
return ctx.body;
}
if (isStream(ctx.body)) {
// a stream can only be read once, so after reading it assign
// the string response to the body so that it can be accessed
// again later
try {
const bodyBuffer = await getStream.buffer(ctx.body);
ctx.body = bodyBuffer;
// recursive call will stringify the buffer
return getResponseBody(ctx);
} catch (error) {
if (error instanceof RequestCancelledError) {
throw error;
}
if (requestCanceled) {
throw new RequestCancelledError();
}
throw error;
}
}
return ctx.body as string;
}
Example #10
Source File: addProgress.ts From tezos-academy with MIT License | 6 votes |
addProgress = async (ctx: Context, next: Next): Promise<void> => {
const addProgressArgs = plainToClass(AddProgressInputs, ctx.request.body, { excludeExtraneousValues: true })
await validateOrReject(addProgressArgs, { forbidUnknownValues: true }).catch(firstError)
const { chapterDone } = addProgressArgs
const user: User = await authenticate(ctx)
await rateLimit(user._id)
await UserModel.updateOne(
{ _id: user._id },
{ $addToSet: { progress: chapterDone } },
).exec()
const updatedUser: User = await UserModel.findOne(
{ _id: user._id },
).lean() as User
const publicUser: PublicUser = toPublicUser(updatedUser)
const response: AddProgressOutputs = { user: publicUser }
ctx.status = 200
ctx.body = response
await next()
}
Example #11
Source File: info.ts From Koa-GraphQL-Template with MIT License | 6 votes |
saveInfo = async (ctx: Context) => {
const body = ctx.request.body;
const info = new InfoModal(body);
const saveResult = await info.save();
if (saveResult) {
ctx.body = {
success: true,
info: saveResult
};
} else {
ctx.body = {
success: false
};
}
}
Example #12
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 #13
Source File: hexo.ts From hexon with GNU General Public License v3.0 | 6 votes |
router.put("/page/:source", async (ctx: Context) => {
const hexo = container.resolve(HexoService)
const { source } = ctx.params
const { raw } = ctx.request.body
if (!source || !raw) {
ctx.status = 400
ctx.body = "need `source` and `raw`"
return
}
ctx.body = await hexo.update(source, raw, "page")
})
Example #14
Source File: errorMiddleware.ts From bluebubbles-server with Apache License 2.0 | 6 votes |
ErrorMiddleware = async (ctx: Context, next: Next) => {
try {
await next();
} catch (ex: any) {
// Log the error, no matter what it is
let errStr = `API Error: ${ex?.message ?? ex}`;
if (ex?.error?.message) {
errStr = `${errStr} -> ${ex?.error?.message}`;
}
if (ex?.data) {
errStr = `${errStr} (has data: true)`;
}
Server().log(errStr, "debug");
if (ex?.stack) {
Server().log(ex?.stack, "debug");
}
// Use the custom HTTPError handler
if (ex instanceof HTTPError) {
const err = ex as HTTPError;
ctx.status = err.status;
ctx.body = err.response;
} else {
ctx.status = 500;
ctx.body = createServerErrorResponse(
ex.message,
ErrorTypes.SERVER_ERROR,
"An unhandled error has occurred!"
);
}
}
}
Example #15
Source File: ErrorHandler.ts From node-experience with MIT License | 6 votes |
static async handle(ctx: Context, next: () => Promise<any>)
{
try
{
await next();
}
catch (err)
{
const responder = new Responder();
const exception: ErrorHttpException = ErrorExceptionMapper.handle(err);
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test')
{
Logger.trace(err.stack);
}
responder.error(exception, ctx, exception.statusCode);
}
}
Example #16
Source File: koa-cors.ts From aiyou-wechaty-robot with Mozilla Public License 2.0 | 6 votes |
koaCors = async (ctx: Context, next) => {
const origin = parse(ctx.get('origin') || ctx.get('referer') || '');
if (origin.protocol && origin.host) {
ctx.set('Access-Control-Allow-Origin', `${origin.protocol}//${origin.host}`);
ctx.set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
ctx.set('Access-Control-Allow-Headers', 'X-Requested-With, User-Agent, Referer, Content-Type, Cache-Control,accesstoken');
ctx.set('Access-Control-Max-Age', '86400');
ctx.set('Access-Control-Allow-Credentials', 'true');
}
if (ctx.method !== 'OPTIONS') {
await next();
} else {
ctx.body = '';
ctx.status = 204;
}
}
Example #17
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 #18
Source File: hexo.ts From hexon with GNU General Public License v3.0 | 6 votes |
router.get("/post/:source", async (ctx: Context) => {
const hexo = container.resolve(HexoService)
const { source } = ctx.params
if (!source) {
ctx.status = 400
ctx.body = "need `source`"
}
const post = await hexo.getPostBySource(decodeURIComponent(source))
if (!post) throw new PostOrPageNotFoundError("post")
ctx.body = post
})
Example #19
Source File: HmrPlugin.ts From web with MIT License | 5 votes |
transformCacheKey(context: Context) {
const mod = this._getOrCreateModule(context.path);
if (mod.needsReplacement) {
const marker = context.URL.searchParams.get('m') ?? Date.now();
return `${context.path}${marker}`;
}
}
Example #20
Source File: hexo.ts From hexon with GNU General Public License v3.0 | 5 votes |
router.get("/categories", async (ctx: Context) => {
const hexo = container.resolve(HexoService)
ctx.body = await hexo.listCategory()
})
Example #21
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 #22
Source File: hexo.ts From hexon with GNU General Public License v3.0 | 5 votes |
router.get("/tags", async (ctx: Context) => {
const hexo = container.resolve(HexoService)
ctx.body = await hexo.listTag()
})
Example #23
Source File: index.ts From cli with MIT License | 5 votes |
async transform(
ctx: Context,
next: () => Promise<any>,
invoke: InvokeCallback
) {
ctx.body = '123';
}
Example #24
Source File: Responder.ts From node-experience with MIT License | 5 votes |
public sendStream(fileDto: IFileDTO, ctx: Context & any, status: IHttpStatusCode)
{
ctx.status = status.code;
ctx.response.set('Content-Type', fileDto.metadata.mimeType);
return ctx.body = fileDto.stream;
}
Example #25
Source File: koa-api-error-response.ts From aiyou-wechaty-robot with Mozilla Public License 2.0 | 5 votes |
koaError = async function (ctx: Context, next) {
try {
await next();
} catch (_err) {
const err = _err || new Error('Null or undefined error');
throw (err);
}
}
Example #26
Source File: sanitize.ts From tezos-academy with MIT License | 5 votes |
sanitize = () => async (ctx: Context, next: Next): Promise<void> => {
const body = JSON.stringify(ctx.request.body)
const forbidden = new RegExp('<|>', 'i')
if (forbidden.test(body)) throw new ResponseError(400, 'Forbidden characters')
else await next()
}
Example #27
Source File: index.ts From cli with MIT License | 5 votes |
async transform(
ctx: Context,
next: () => Promise<any>,
invoke: InvokeCallback
) {
const { invokeOptions, invokeFun = invoke } =
await parseInvokeOptionsByOriginUrl(this.options, ctx.request, invoke);
if (!invokeOptions.functionName) {
await next();
} else {
try {
const result: {
headers: any;
statusCode: number;
body: string;
isBase64Encoded: boolean;
} = await invokeFun({
functionDir: invokeOptions.functionDir,
functionName: invokeOptions.functionName,
functionHandler: invokeOptions.functionHandler,
data: invokeOptions.data,
sourceDir: invokeOptions.sourceDir,
incremental: true,
verbose: invokeOptions.verbose,
});
let data;
ctx.status = result.statusCode;
if (result.isBase64Encoded) {
// base64 to buffer
data = Buffer.from(result.body, 'base64');
} else {
try {
data = JSON.parse(result.body);
} catch (err) {
data = result.body;
}
}
for (const key in result.headers) {
ctx.set(key, getHeaderValue(result.headers, key));
}
ctx.body = data;
} catch (err) {
ctx.body = err.stack;
ctx.status = 500;
}
await next();
}
}
Example #28
Source File: transformModuleImportsPlugin.ts From web with MIT License | 5 votes |
async function transformModuleImportsWithPlugins(
logger: Logger,
context: Context,
jsCode: string,
rootDir: string,
resolvePlugins: Plugin[],
) {
const filePath = path.join(rootDir, toFilePath(context.path));
async function resolveImport(source: string, code: string, column: number, line: number) {
for (const plugin of resolvePlugins) {
const resolved = await plugin.resolveImport?.({ source, context, code, column, line });
if (typeof resolved === 'string') {
logger.debug(
`Plugin ${plugin.name} resolved import ${source} in ${context.path} to ${resolved}.`,
);
return resolved;
}
if (typeof resolved === 'object') {
logger.debug(
`Plugin ${plugin.name} resolved import ${source} in ${context.path} to ${resolved.id}.`,
);
return resolved.id;
}
}
}
async function transformImport(source: string, code: string, column: number, line: number) {
let resolvedImport = (await resolveImport(source, code, column, line)) ?? source;
for (const plugin of resolvePlugins) {
const resolved = await plugin.transformImport?.({
source: resolvedImport,
context,
column,
line,
});
if (typeof resolved === 'string') {
logger.debug(
`Plugin ${plugin.name} transformed import ${resolvedImport} in ${context.path} to ${resolved}.`,
);
resolvedImport = resolved;
}
if (typeof resolved === 'object' && typeof resolved.id === 'string') {
logger.debug(
`Plugin ${plugin.name} transformed import ${resolvedImport} in ${context.path} to ${resolved.id}.`,
);
resolvedImport = resolved.id;
}
}
return resolvedImport;
}
return transformImports(jsCode, filePath, transformImport);
}
Example #29
Source File: koa-not-found.ts From aiyou-wechaty-robot with Mozilla Public License 2.0 | 5 votes |
koaNotFound = async function (ctx: Context) {
ctx.response.type = 'text/html';
ctx.response.body = '<h1>error: api or url not found!</h1>';
}