Node.js - api.route.put()
Register a handler for HTTP PUT requests to the route.
import { api } from '@nitric/sdk'
const PARAM_ID = 'customerId'
const customerRoute = api('public').route(`/customers/:${PARAM_ID}`)
customerRoute.put((ctx) => {
// construct response for the PUT: /customers/:customerId request...
const responseBody = {}
ctx.res.json(responseBody)
})
Parameters
- Name
middleware
- Required
- Required
- Type
- HttpMiddleware | HttpMiddleware[]
- Description
One or more middleware services to use as the handler for HTTP requests. Handlers can be sync or async
- Name
opts
- Optional
- Optional
- Type
- object
- Description
Additional options when creating method.
- Name
security
- Optional
- Optional
- Type
- map<string, string[]>
- Description
Security rules to apply with scopes to the entire API. Keys must match a
securityDefinition
.
Examples
Register a handler for PUT requests
import { api } from '@nitric/sdk'
const PARAM_ID = 'customerId'
const customerRoute = api('public').route(`/customers/:${PARAM_ID}`)
customerRoute.put((ctx) => {
const id = ctx.req.params[PARAM_ID]
// handle the PUT request...
const responseBody = {}
ctx.res.json(responseBody)
})
Chain services as a single method handler
When multiple services are provided they will be called as a chain. If one succeeds, it will move on to the next. This allows middleware to be composed into more complex handlers.
import { api } from '@nitric/sdk'
import { validate } from '../middleware'
const PARAM_ID = 'customerId'
const putCustomer = (ctx) => {
const id = ctx.req.params[PARAM_ID]
// handle the PUT request...
const responseBody = {}
ctx.res.json(responseBody)
}
const customerRoute = api('public').route(`/customers/:${PARAM_ID}`)
customerRoute.put([validate, putCustomer])
Access the request body
The PUT request body is accessible from the ctx.req
object.
import { api } from '@nitric/sdk'
const customerRoute = api('public').route(`/customers/:${PARAM_ID}`)
customerRoute.put((ctx) => {
const customerData = ctx.req.data
// parse, validate and store the request payload...
})