Papupata Documentation

API Reference

class DeclaredAPI

method implementWithMiddleware

Purpose

Implements an API using express. This variant allows for inclusion of middleware for the implementation.

Usage

Instead of calling the methods on an express app or router yourself, you use this function to have papupata do it for you.

Parameters

NameTypeDescription
middleware
{
  express?: Function[]
  papupata?: Function[]
}

An object with arrays of express and papupata middleware functions. Both arrays are optional.

In versions prior to 1.5.0, this parameter was an array of express middleware. This is still supported, but is considered to be deprecated. You can use the implementWithExpressMiddleware instead as it specifically implements the old interface of implementWithMiddleware.

implementationFunctionA function that implements the route. Specified as follows

Parameters

NameTypeDescription
reqRequestThis is a typed express request -- that is, body, params and query have been replaced with typed versions of themselves.
resResponseExpress response corresponding to the request.

Returns

ResponseType, ServerResponseType, or a promise of either
  • Do note that the "next" parameter typically used in routes is not present
  • Anything thrown (includes returned rejected promises) is given to the usual next function
  • If undefined is returned, nothing is sent automatically. This could at times explain hanging requests. Of course, unless you explicitly declared the API to return undefined, you should see type errors, too.

Returns

Nothing

Caveats

  • Either application of router must be configured or the function throws
  • You can implement an API multiple times, but it is unlikely to do you any good.
  • There is at this time no way to cleanly implement an API that does not just return its value, and instead, say, streams it.

Examples

Older styles are still supported in later versions, just not preferred.
Declaration
import { APIDeclaration } from 'papupata'
const api = new APIDeclaration()
const myAPI = api.declarePostAPI('/do-stuff/:param')
  .params({param: String})
  .query({q: String})
  .body<{key: string}>()
  .response<string>()
Usage in implementation
myAPI.implementWithMiddleware(
  {
    express: [
      (req, _res, next) => {
        console.log(req.url)
        next()
      }
    ],
    papupata: [
      (req, _res, _route, next) => {
        console.log(req.url)
        next()
      }
    ]
  },
  () => {
    return 'hello'
  }
)
Usage in invocation
const response = await myAPI({param: 'abc', q: 'def', key: 'ghi'})
// Response in the example will be abc,def,ghi