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

ts-router

v0.2.6

Published

koa router middleware, typescript fully supported, jersey like coding

Downloads

122

Readme

Node version NPM version build status Test coverage Dependencies

Installation

$ npm install ts-router

ts-router is supported in node v4+ with --harmony flag.

Introduction

This project is developed in typescript, and usable in typescript. It serves as a routing middleware for koa@next.

More documentations will be added soon, for immediate access to all features, please refer to the declaration file.

PRs and Issues are welcome

Example

/// <reference path="./typings/ts-router/ts-router.d.ts"/>
/// <reference path="./typings/koa/koa.d.ts"/>


import {Before, Consume, MediaType, Response, Controller, Router, Path, POST, QueryParam, PathParam, BodyParam} from 'ts-router';
import * as Koa from 'koa';


const app = new Koa();
const router = new Router();

@Path('/user')
class UserRoute extends Controller {
    private user:User;
    @PathParam('_id') userId:string;

    constructor() {
        super();
        //The controller will be created upon each request, so it is safe to initialize variables here for all other routes.
        this.user = getFromMemoryCache();
    }

    @Before
    async getUserBeforeAll(@PathParam('_id') userId:string) {
        this.user = await dbAction({_id: this.userId});
    }

    @Path('/:_id')
    @POST
    @Consume(MediaType.JSON)
    async updateUser(@QueryParam('name') name:string,
        @BodyParam('password') password:string):Promise<Response> {
        this.user.name = name;
        this.user.password = password;
        await user.save();
        return Response.status(200).body('success').build();
    }
}

router.use(UserRoute);
app.use(router.routes());
app.listen(3000);

console.log('started');

API

Main

Controller

This is where you get started, have a class extends it.

    class Test extends Controller {

    }

Router

This is the central part where all Controllers are controlled.

    class Test extends Controller {
    }
    let router = new Router();
    router.use(Test);
    let app = new Koa();
    app.use(router.routes());

ResponseBuilder

This is a helper class builds Response.

  • status(number | Response.Status) - set response status.
  • header(string,string) - set header.
  • type(MediaType) - set return type.
  • body(any) - it can be an object (can be compiled using JSON.stringify) or string.
  • allow(...methods: (string | HttpMethod)[]) - set Allow header.
  • charset(Charset | string) - set charset of response body.
  • expires(Date) - set Expires header.
  • lastModified(Date) - set Last-Modified header.
  • cookie(Cookie) - set cookie to be returned from the response.
  • build():Response - finish building Response.

Response

This is to be returned from a route;

  • static status(number | Response.Status) - set response status and returns the build helper.
  • body: any - property.
  • status: number - property.
  • headers: { [key:string] : string} - property.
  • send(Context) - to send response to the client.

Context

This extends Koa.IContext

  • cookie: Cookie - property.
  • params: Object - property, parsed path params.
  • requestBody: any - property, parsed request body.

Cookie

Cookie object

  • content: string - property. e.g, sessionId: 12345678.
  • path: string - property.
  • secure: boolean - property.
  • httpOnly: boolean - property.
  • expires: Date - property.
  • maxAge: number - property.
  • toString():string - parse the cookie object to Set-Cookie header value.

Annotations

@Before

method decorator, to be ran before all other routes.

@After

method decorator, to be ran after all other routes.

@GET

method decorator, set the route method to GET.

@POST

method decorator, set the route method to POST.

@PUT

method decorator, set the route method to PUT.

@DELETE

method decorator, set the route method to DELETE.

@Inject(Function)

method decorator, run before route and after controller before wares.

@Path(string)

method decorator, set the route path. (Can be applied multiple times on one route).

    @Path('/index')
    @Path('/')
    async index():Promise<Response> {
        return Response.status(200).build();
    }
    // both '/index' and '/' will be directed to this route.

@Produce(MediaType)

method decorator, set Content-Type of response.

@Consume(MediaType)

method decorator, set to be processed body content type, and parse it accordingly.

@QueryParam(string)

property or parameter decorator, retrieve query variable with provided key.

@PathParam(string)

property or parameter decorator, retrieve params variable with provided key.

@HeaderParam(string)

property or parameter decorator, retrieve header variable with provided key.

@BodyParam(string)

property or parameter decorator, retrieve body variable with provided key.

@Query

property or parameter decorator, retrieve the whole query.

@Params

property or parameter decorator, retrieve all params.

@Headers

property or parameter decorator, retrieve all headers.

@Body

property or parameter decorator, retrieve the whole body.

@AppContext

property or parameter decorator, retrieve Context object of current route.

@HttpContext

property or parameter decorator, retrieve Koa Context.

@RouteResponse

parameter decorator, retrieve the response after executing route (used in @Before mostly).

Misc

mediaTypeToString(MediaType): string

parse MediaType to string. e.g, MediaType.JSON to application/json.

enum Charset

  • UTF8

enum HttpMethod

  • GET
  • POST
  • PUT
  • DELETE

enum MediaType

  • TEXT
  • MULTIPART
  • JSON
  • FORM

enum Response.Status

  • ACCEPTED - 202.
  • BAD_GATEWAY - 502.
  • BAD_REQUEST - 400.
  • CONFLICT - 409.
  • CREATED - 201.
  • EXPECTATION_FAILED - 417.
  • FORBIDDEN - 403.
  • FOUND - 302.
  • GATEWAY_TIMEOUT - 504.
  • GONE - 410.
  • HTTP_VERSION_NOT_SUPPORTED - 505.
  • INTERNAL_SERVER_ERROR - 500.
  • LENGTH_REQUIRED - 411.
  • METHOD_NOT_ALLOWED - 405.
  • MOVED_PERMANENTLY - 301.
  • NO_CONTENT - 204.
  • NOT_ACCEPTABLE - 406.
  • NOT_FOUND - 404.
  • NOT_IMPLEMENTED - 501.
  • NOT_MODIFIED - 304.
  • OK - 200.
  • PARTIAL_CONTENT - 206.
  • PAYMENT_REQUIRED - 402.
  • PRECONDITION_FAILED - 412.
  • PROXY_AUTHENTICATION_REQUIRED - 407.
  • REQUEST_ENTITY_TOO_LARGE - 413.
  • REQUEST_TIMEOUT - 408.
  • REQUEST_URI_TOO_LONG - 414.
  • REQUESTED_RANGE_NOT_SATISFIABLE - 416.
  • RESET_CONTENT - 205.
  • SEE_OTHER - 303.
  • SERVICE_UNAVAILABLE - 503.
  • TEMPORARY_REDIRECT - 307.
  • UNAUTHORIZED - 401.
  • UNSUPPORTED_MEDIA_TYPE - 415.
  • USE_PROXY = 305

License

The MIT License (MIT) Copyright (c) <2016>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.