當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript koa.Context類代碼示例

本文整理匯總了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);
};
開發者ID:easygenerator,項目名稱:lrs,代碼行數:10,代碼來源:verifyXapiVersion.ts

示例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}`);
  }
};
開發者ID:whosesmile,項目名稱:koa-scaffold,代碼行數:50,代碼來源:error.ts

示例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;
  }
};
開發者ID:whosesmile,項目名稱:koa-scaffold,代碼行數:15,代碼來源:favicon.ts

示例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();
  }
};
開發者ID:easygenerator,項目名稱:lrs,代碼行數:15,代碼來源:cors.ts

示例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()
})
開發者ID:el1t,項目名稱:silo-server,代碼行數:16,代碼來源:app.ts

示例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('&')}`)
}
開發者ID:YimYijet,項目名稱:WebTest,代碼行數:7,代碼來源:router.ts

示例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)
    }
})
開發者ID:YimYijet,項目名稱:WebTest,代碼行數:9,代碼來源:router.ts

示例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;
  }
};
開發者ID:easygenerator,項目名稱:lrs,代碼行數:10,代碼來源:verifyAppApiKey.ts

示例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,
    });
  };
開發者ID:Canner,項目名稱:canner,代碼行數:19,代碼來源:loggerMiddleware.ts

示例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);
};
開發者ID:coderfox,項目名稱:Another-SS-Panel,代碼行數:10,代碼來源:index.ts


注:本文中的koa.Context類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。