1.2.6 • Published 6 years ago

route-type-compiler v1.2.6

Weekly downloads
1
License
ISC
Repository
-
Last release
6 years ago

Route Type Compiler

Compiler d.ts for route file on server side, then use the d.ts for you request on client side!

It's pretty useful to get type protect in restful http communication

Usage

1.In the server side, we have a route like this:

import {Controller, HttpMethod, route} from 'koa-decorator';
import ITodo from '@server/declaration/Todo';
import {Context} from 'koa';

@route('/demo')
export default class DemoCtrl extends Controller {

  @route('/', HttpMethod.GET)
  async alive(): Promise<{text: string}> {
    return {text: 'hello world'};
  }

  /**
   * 使用原生 koa 返回数据
   */
  @route('/koa', HttpMethod.GET)
  async koa(ctx: Context) {
    ctx.body = '123';
  }

  @route('/error/path/somepath', HttpMethod.GET, other)
  async error(): Promise<ITodo[]> {
    throw {
      code: 12345,
      msg: '出错了',
      data: {
        userId: 'Tom',
      },
    };
  }

  @route('/koa', HttpMethod.POST)
  async koaPost(ctx: Context) {
    const data = ctx.request.body;
    
    return {
      koa: 'fun in koa',
      data,
    }
  }
}

2. Compile the d.ts for the route file dependent on path and method type

route.d.ts

/*
* Autogenerated by Route Type Compiler (1.2.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
*/
/* tslint:disable */

import ApiDemo from '../route/api/demo';
import Demo from '../route/demo';

declare module 'test' {
  const apiDemo: ApiDemo;
  const demo: Demo;
  export interface IGetRoute {
    'api/demo/': ReturnType<typeof apiDemo.alive >;
    'api/demo/koa': ReturnType<typeof apiDemo.koa >;
    'api/demo/error/path/somepath': ReturnType<typeof apiDemo.error >;
    '/demo/': ReturnType<typeof demo.alive >;
    '/demo/koa': ReturnType<typeof demo.koa >;
    '/demo/error/path/somepath': ReturnType<typeof demo.error >
  }
  export interface IPostRoute {
    'api/demo/koa': ReturnType<typeof apiDemo.koaPost >;
    '/demo/koa': ReturnType<typeof demo.koaPost >
  }
}

3.Then test module have all the route file type, use test module on client side.

1.2.6

6 years ago

1.2.5

6 years ago

1.2.4

6 years ago

1.2.3

6 years ago

1.2.2

6 years ago

1.2.1

6 years ago

1.2.0

6 years ago

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago