uMethod

What it does

Defines a function as a request handler.

How to use
@uMethod.get()
sayHello(req: uRequest, res: uResponse): void {
    res.send('Hello World')
}

Supported methods:

@uMethod.get(path?: string)
@uMethod.post(path?: string)
@uMethod.put(path?: string)
@uMethod.patch(path?: string)
@uMethod.delete(path?: string)
Description

Foo

Example

import * as bodyParser from 'body-parser'
import { ... } from 'microdose'

@uRouter({
  middleware: [
    bodyParser.json()
  ]
})
class Router {

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

    @uMethod.post()
    addToGuestList(req: uRequest, res: uResponse): 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
        })
    }

    @uMethod.put('/:blokesName')
    renamePerson(req: uRequest, res: uResponse): 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
        })
    }
}

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 ""