Skip to content

Commit

Permalink
feat(tsd): add ctx.logger and logger.error support Error object (#1108)
Browse files Browse the repository at this point in the history
  • Loading branch information
shepherdwind authored and popomore committed Jun 26, 2017
1 parent 7c2e436 commit daa8227
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
11 changes: 10 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ export interface Logger {
info(info: string, ...args: string[]): void;
warn(info: string, ...args: string[]): void;
debug(info: string, ...args: string[]): void;
error(info: string, ...args: string[]): void;
error(info: string | Error, ...args: string[]): void;
}

export type RequestArrayBody = any[];
export type RequestObjectBody = { [key: string]: any };
interface Request extends KoaApplication.Request { // tslint:disable-line
/**
* detect if response should be json
Expand Down Expand Up @@ -116,6 +118,8 @@ interface Request extends KoaApplication.Request { // tslint:disable-line
* ```
*/
query: { [key: string]: string };

body: RequestArrayBody | RequestObjectBody;
}

interface Response extends KoaApplication.Response { // tslint:disable-line
Expand Down Expand Up @@ -724,6 +728,11 @@ export interface Context extends KoaApplication.Context {
*/
curl(url: string, opt: any): Promise<any>;

/**
* Get logger by name, it's equal to app.loggers['name'], but you can extend it with your own logical
*/
getLogger(name: string): Logger;

/**
* Render a file by view engine
* @param {String} name - the file path based on root
Expand Down
15 changes: 12 additions & 3 deletions test/fixtures/apps/app-ts/app/controller/foo.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Controller } from 'egg';
import { Controller, RequestObjectBody } from 'egg';

// add user controller and service
declare module 'egg' {
Expand All @@ -10,9 +10,18 @@ declare module 'egg' {
// controller
export default class FooController extends Controller {
async getData() {
this.ctx.body = await this.ctx.service.foo.bar();
try {
this.ctx.body = await this.ctx.service.foo.bar();
} catch (e) {
const body: RequestObjectBody = this.ctx.request.body;
this.app.logger.info(e.name, body.foo);
}
}
async getBar() {
this.ctx.body = await this.service.foo.bar();
try {
this.ctx.body = await this.service.foo.bar();
} catch (e) {
this.ctx.logger.error(e);
}
}
}

0 comments on commit daa8227

Please sign in to comment.