0.9.9 • Published 3 years ago

@peregrine/koa-with-decorators v0.9.9

Weekly downloads
11
License
MIT
Repository
github
Last release
3 years ago

Node.js linter & tests Node.js deployment Quality Gate Status license npm node version types

Koa with decorators

Library for using Koa with decorators

Notes

  • Make sure to enable and set the experimentalDecorators flag to true in your tsconfig.json

Decorators

decoratortyperequiredaliasesdescription
@HttpGetmethodyes@GETListen for HTTP GET requests
@HttpPostmethodyes@POSTListen for HTTP POST requests
@HttpPutmethodyes@PUTListen for HTTP PUT requests
@HttpPatchmethodyes@PATCHListen for HTTP PATCH requests
@HttpDeletemethodyes@DELETEListen for HTTP DELETE requests
@HttpOptionsmethodyes@OPTIONSListen for HTTP OPTIONS requests
@HttpHeadmethodyes@HEADListen for HTTP HEAD requests
@HttpAllmethodonly if @Path is not setListen for all HTTP requests
@Path(path: string)methodno (default path is /)Attaches the method to the specified path
@Controller(path: string)classno (default path is /)Adds a prefix to all paths in this method

Demo

import { HttpGet, HttpPost, Path, Controller, createRouter, DefaultStatusCode, CachedFor } from "@peregrine/koa-with-decorators"
import Koa, { Context } from "koa"
import Router from "@koa/router"
import bodyParser from "koa-bodyparser"

interface Pet {
    id: number
    name: string
    kind: string
}

@Controller("pets")
class PetsController {
    public constructor(private readonly petsList: Pet[]) {}

    @HttpGet
    @DefaultStatusCode(200)
    @CachedFor(4, "minutes")
    public getAllPets({ response }: Context): void {
        response.body = this.petsList
    }

    @HttpGet
    @Path("/:id")
    @DefaultStatusCode(200)
    @CachedFor(4, "minutes")
    public getPetById(ctx: Context): void {
        const petId = parseInt(ctx.params.id)
        const pet = this.petsList.find(it => it.id === petId) ?? null

        if (pet !== null) {
            ctx.response.body = pet
        } else {
            ctx.response.status = 404
        }
    }

    @HttpPost
    @DefaultStatusCode(201)
    public addPet(ctx: Context): void {
        const newPet = ctx.request.body
        this.petsList.add(newPet)
        ctx.response.body = newPet
    }
}

const myPets: Pet[] = [{ id: 1, name: "Maya", kind: "Macaw" }]

const petsRouter: Router = createRouter(new PetsController(myPets))

const koa = new Koa()
koa.use(bodyParser())

koa.use(petsRouter.routes())
koa.use(petsRouter.allowedMethods())

koa.listen(8080)
0.9.9

3 years ago

0.9.8

3 years ago

0.9.6

3 years ago

0.9.5

3 years ago

0.9.4

3 years ago

0.9.3

3 years ago

0.9.2

3 years ago

0.9.1

3 years ago

0.9.0

3 years ago

0.1.2

4 years ago

0.1.1

4 years ago