MicroMethod

What it does

Defines a function as a request handler.

How to use
@MicroMethod.Get()
sayHello(req: MicroRequest, res: MicroResponse): void {
    res.send('Hello World')
}

Supported methods:

@MicroRouter.Get(path?: string | MiddlewareFunction, middleware?: MiddlewareFunction)
@MicroRouter.Post(path?: string | MiddlewareFunction, middleware?: MiddlewareFunction)
@MicroRouter.Put(path?: string | MiddlewareFunction, middleware?: MiddlewareFunction)
@MicroRouter.Patch(path?: string | MiddlewareFunction, middleware?: MiddlewareFunction)
@MicroRouter.Delete(path?: string | MiddlewareFunction, middleware?: MiddlewareFunction)
Description

Foo

Example

@MicroRouter()
class MyRouter {

    // For demo only. State will be lost on app restart
    partyPeople: string[] = ['Freddy', 'Brian', 'Roger'];

    @MicroMethod.Post()
    addToGuestList(req: MicroRequest, res: MicroResponse): void {
        const person = req.body.person
        this.partyPeople.push(person)
        res.status(201).send({
            message: person + ' has been added to the guest list',
            people: this.partyPeople
        })
    }

    @MicroMethod.Put('/:blokesName')
    renamePerson(req: MicroRequest, res: MicroResponse): void {
        // From PUT request payload
        const newName = req.body.new_name
        const blokeIndex = this.partyPeople.indexOf(req.params.blokesName)
        const blokeToBeReplaced = this.partyPeople[blokeIndex]
        this.partyPeople[blokeIndex] = newName
        res.send({
            message: blokeToBeReplaced + ' has been replaced with ' + newName,
            people: this.partyPeople
        })
    }
}

MicroBootstrap(MyRouter)

Test it

$ curl -H "Content-Type: application/json" -d "{\"person\": \"John\"}" -X POST http://localhost:3000
$ {
$     message: "John has been added to the guest list",
$     people: ['Freddy', 'Brian', 'Roger', 'John']
$ }
$ curl -H "Content-Type: application/json" -d "{\"new_name\": \"Johnny\"}" -X PUT http://localhost:3000/John
$ {
$     message: "John has been replaced with Johnny",
$     people: ['Freddy', 'Brian', 'Roger', 'Johnny']
$ }

results matching ""

    No results matching ""