npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

koa-ts-decorator-router

v0.1.8

Published

you can via typescript class decorator to define koa-routers.

Downloads

16

Readme

koa-ts-decorator-router

You can via typescript class and decorator to difine your koa-router's routes middleware for Koa.

Features

You can define your koa-router's routes by es6 class. like this

@Controller({
  path: "user",
})
export class UserController {
  login({ name }: User) {
    console.log("param", name);
    return name;
  }

  @Method({
    path: "myRegister",
    method: "POST",
  })
  async register({ name, pass }: User) {
    const user = new User();
    user.name = name;
    user.pass = pass;
    await mysql().getRepository(User).save(user);
    return user;
  }
}

This will be transfer to koa-route like:

const Router = require("@koa/router");
const router = new Router();

router.get("/user/login", async (ctx, next) => {
  ctx.body = name; //name is abave class UserController login returned
  await next();
});

router.post("/user/myRegister", async (ctx, next) => {
  ctx.body = user;
  await next();
});

Installation

# npm ..
npm i koa-ts-decorator-router
# yarn ..
yarn add koa-ts-decorator-router

API

ClassifyKoaRouter ⏏

Kind: Exported function

| Param | Type | Description | | ---------------- | ------------------- | ---------------------- | | [router] | Object | instance of koa-router | | [scanController] | Ojbect | scan controller config | | [otherOpts] | Ojbect | other config |

scanController Type

type ScanControllerOpts = {
  dirname: string; // your Controller ts file dir
  filter: RegExp; //filter you need regist to koa-router
};

otherOpts Type

type OtherOpts = {
  convertDigital?: boolean; // is try convert param string to number.
  assignQuery?: boolean; // is Object.assign ctx.request.query to ctx.request.body when body is Object type.
  logRoute?: boolean; // console.log register route, while you debug app you can turn on this config.
  /**
   * if return ture, will be call method. else not call method and ctx.body will be set to you function return value.
   *  */
  onBeforeCallMethod?: (
    ctx: ParameterizedContext,
    methodConf: {
      fullPath: string;
      method: MethodType;
      customConf?: T;
    },
  ) => unknown;
};

Controller Decorator ([controllerDecoratorOpts])

controllerDecoratorOpts Type

type ControllerDecoratorConf = {
  path?: string;
};
  • Notice: if you not offer path, while register koa-route will it default value will be /.

@Path(path:string)

this decorator can use for controller and method.

@GET(path?:string)

@POST(path?:string)

@PUT(path?:string)

@PATCH(path?:string)

@DELETE(path?:string)

@ALL(path?:string)

@CustomConf(customConf:T)

Controller Method Decorator ([methodDecoratorOpts])

type MethodDecoratorConf<T> = {
  path?: string;
  method?: MethodType;
  customConf?: T;
  rateLimitInstance?: RateLimiterStoreAbstract;
  rateLimitConsumeFn?: {
    (
      rateLimitInstance: RateLimiterStoreAbstract,
      ctx: Koa.ParameterizedContext,
    ): Promise<any>;
  };
};

If you offer RateLimiterStoreAbstract, and rateLimitConsumeFn you can define you function to consume rateLimit.

Controller 's path and Method's path composition to koa-route's path.

eg1:

export class UserController {
  login({ name }: User) {
    console.log("param", name);
    return name;
  }
}

koa-route will be router.get(/login)

eg2:

@Controller({
  path: "user",
})
export class UserController {
  login({ name }: User) {
    console.log("param", name);
    return name;
  }
}

koa-route will be router.get(/user/login)

eg3:

export class UserController {
  @Method({
    method: "POST",
  })
  login({ name }: User) {
    console.log("param", name);
    return name;
  }
}

koa-route will be router.post(/login)

eg5:

@Controller({
  path: "////user//",
})
export class UserController {
  @Method({
    method: "POST",
    path: "//login////",
  })
  login({ name }: User) {
    console.log("param", name);
    return name;
  }
}

koa-route will be router.post(/user/login)

eg6:

@Controller({
  path: "user",
})
export class UserController {
  @Method({
    method: "POST",
    path: "login/:id",
  })
  login({ name }: User) {
    console.log("param", name);
    return name;
  }
}

koa-route will be router.post(/user/login/:id)

Controller Method Param

  • request.body is Array, It will be call login(request.body, ctx.request, router)
  • request.body is Object, And if otherOpt assignQuery is ture . It will be call login(Object.assign(request.body,request.query), ctx.request, router)
  • If method First param is Array or Object, And if otherOpt convertDigital is true. we will try to auto recursion transform param value, convert string to number or float.

Example
Basic usage:

The directory structure

.
├── controllers
│   ├── FileController.ts
│   └── UserController.ts
├── index.ts

index.ts

import Koa from "koa";
import Router from "koa-router";
import KoaBody from "koa-body";

app.use(
  KoaBody({
    multipart: true,
  }),
);

const router = new Router();

app.use(
  ClassifyKoaRouter(router, {
    dirname: path.join(__dirname + "./controllers"), // your Controller ts file dir
    filter: /(.*Controller)\.ts$/, //filter you need regist to koa-router
  }),
);

UserController.ts

@Controller({
  path: "user",
})
export class UserController {
  login({ name }: User) {
    console.log("param", name);
    return name;
  }

  @Method({
    path: "myRegister",
    method: "POST",
  })
  async register({ name, pass }: User) {
    const user = new User();
    user.name = name;
    user.pass = pass;
    await mysql().getRepository(User).save(user);
    return user;
  }
}

Upload usage:

FileController

@Controller({
  path: "file",
})
export class FileController {
  @Method({
    method: "POST",
  })
  upload(params: any, { files }: { files: Files }) {
    return saveFiles(files).map((i) => {
      delete i.filePath;
      return i;
    });
  }
}

Notice

  • Use this lib must be cooperation with koa-body and koa-router.

  • Because lib use typescript decorator, you need allow options at tsconfig.json

"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

Contributing

Please submit all issues and pull requests to the hxdyj/koa-ts-decorator-router repository!

Support

If you have any problem or suggestion please open an issue here.

License

MIT