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

@tng/koa-controller

v1.0.0-alpha.1

Published

Write koa http server with koa-controller by decorator feature in typescript.

Downloads

4

Readme

@tng/koa-controller

Write koa http server with koa-controller by decorator feature in typescript. Make job easily done in a short time.

Usage Example

// path/to/controller.ts
import { controller, get } from '@tng/koa-controller'

@controller('/api')
class UserController {
  @get('/login')
  async login() {
    return 'OK'
  }
}

// path/to/main/koa/server.ts
import { getRouterSync } from '@tng/koa-controller'
const app = new Koa()

// inject all related controller files by given glob pattern
app.use(getRouterSync({
  files: path.resolve('path/to/controller/**/*.[jt]s'),
}).routes())

Router

@controller(prefix?: string)

Register a route on a class for router as a controller.

NOTE The router will ignore the route if no route method is provided in the class. And for the contrast, the route method will be ignored unless the controller is registed.

@request(verb: string, route: string)

Register a route on a method for router. It will run other middleware as well when route is matched. The sequence is in middleware squence section.

Method's first parameter is the state of context, or ctx.state; second paramenter is the koa context or ctx for the request. Method should be a thenable async function which return the result for response body.

NOTE A method can be registered for multi routes. all the result and the middlewares will be shared.

example:

class SomeController {
  @request('get', '/login')
  async somePath(state, ctx: Context) {
    // state is for context.state
    // ctx is for context
    return result // equivalent to ctx.body = result
  }
}

@before((ctx: KoaContext) => Promise<void>)

@after((ctx: KoaContext) => Promise<void>)

@middleware((ctx: KoaContext, next: Promise<void>) => Promise<void>)

Register a before middleware, a after middleware or a middleware for a route which register either on method or controller class.

middleware sequence

if same decorator written 2 or more times, router will run in sequence from top to bottom. Please see test/router.test.ts file to learn more about it.

  • controller @middleware | @before
  • method @middleware | @before
  • method function
  • method @after
  • controller @after

@get(pathname: string)

@post(pathname)

The shortcut for @request('get', pathname) and @request('post', pathname)

getRouterSync(options): KoaRouter

Run require to require files and return koa router instance.

  • options: <Object>
    • files: <String> glob pattern to run Nodejs's require function. glob will base on cwd option.
    • cwd: <String> base working directory to run require function. Default is process.cwd().
    • prefix: <String> Koa Router contructor's parameter to generate Koa Router.
    • logger: <Logger> Logger has debug or info method to debug file or functions.

Logger (TODO)

Tracer

Use opentracing implemented tracer instance to cross-platform tracing.

traceMW(tracer: Tracer, options?): KoaMiddleware

WIP: Use opentracing implemented tracer instance to cross-platform tracing.

Validate

@validate(schema: JSONSchema, { ajv: AjvInstance })

Generate a @before middleware to register on a method or controller by using AJV.

Example

@validate({
  type: 'object',
  require: ['query'],
  properties: {
    query: {
      type: 'object',
      require: ['id'],
      properties: {
        id: { type: 'integer' },
      }
    }
  }
})
class SomeController { ... }

@validateState(schema: JSONSchema, { ajv: AjvInstance })

Generate a @before middleware to register on a method or controller by using AJV but ONLY validate ctx.state. It should be always be used with @state()

state

@state(map: {[key: string]: PathFromContext/String })

Generate ctx.state from ctx.query, ctx.params and ctx.request.body if map is undefined. If map is provided only mapped key-value pair will be included into state.

The key in map will be the key in state. The value in map will be resolved the value in state by finding the value of context in a certain path. Value path maybe provided in a array. It means the order to find a value from context.

example

class UserController {
  @get('/users/:id')
  @state({
    userId: ['params.id'],
    age: ['query.name'],
    token: ['header.authorization'],
  })
  async getUserInfo(state) {
    // GET /users/123?name=John&age=18
    state = {
      userId, // 123 (string)
      name, // John
      // age will not be in the state
      token, // token is undefined unless it passed.
    }
  }
}

Error Handler (TODO)

Contribution (WIP)