Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
@api-ts/typed-express-router
Advanced tools
A thin wrapper around Express's Router
apiSpec
encode
functionhttpRoute
apiSpec
have an associated route handlerexpress.RequestHandler[]
chain beyond the additional
properties described in Goals
(projects and other libraries can do this)Two very similar functions are provided by this library that respectively create or wrap an Express router:
import { createRouter, wrapRouter } from '@api-ts/typed-express-router';
import express from 'express';
import { MyApi } from 'my-api-package';
const app = express();
const typedRouter = createRouter(MyApi);
app.use(typedRouter);
Once you have the typedRouter
, you can start adding routes by the api-ts api name:
typedRouter.get('hello.world', [HelloWorldHandler]);
Here, HelloWorldHandler
is a almost like an Express request handler, but req
and
res
have an extra property. req.decoded
contains the validated and decoded request.
On the response side, there is an extra res.sendEncoded(status, payload)
function that
will enforce types on the payload and encode types appropriately (e.g.
BigIntFromString
will be converted to a string). The exported TypedRequestHandler
type may be used to infer the parameter types for these functions.
If more flexibility is needed in the route path, a routeAliases
function may be
provided to match multiple paths. These paths may use the full Express matching syntax,
but take care to preserve any path parameters or else you will likely get decode errors.
typedRouter.get('hello.world', [HelloWorldHandler], {
routeAliases: ['/oldDeprecatedHelloWorld'],
});
The createRouter
, wrapRouter
, and individual route methods all take an optional last
parameter where a post-response and error handling function may be provided. Ones
specified for a specific route take precedence over the top-level ones. These may be
used to customize error responses and perform other actions like metrics collection or
logging.
const typedRouter = createRouter(MyApi, {
onDecodeError: (errs, req, res) => {
// Format `errs` however you want
res.send(400).json({ message: 'Bad request' }).end();
},
onEncodeError: (err, req, res) => {
// Ideally won't happen unless type safety is violated, so it's a 500
res.send(500).json({ message: 'Internal server error' }).end();
},
afterEncodedResponseSent: (status, payload, req, res) => {
// Perform side effects or other things, `res` should be ended by this point
endRequestMetricsCollection(req);
},
});
// Override the decode error handler on one route
typedRouter.get('hello.world', [HelloWorldHandler], {
onDecodeError: customHelloDecodeErrorHandler,
});
If you need custom behavior on decode errors that is more involved than just sending an
error response, then the unchecked variant of the router functions can be used. They do
not fail and call onDecodeError
when a request is invalid. Instead, they will still
populate req.decoded
, except this time it'll contain the
Either<Errors, DecodedRequest>
type for route handlers to inspect.
// Just a normal express route
typedRouter.getUnchecked('hello.world', (req, res) => {
if (E.isLeft(req.decoded)) {
console.warn('Route failed to decode! Continuing anyway');
})
res.send(200).end();
});
Middleware added with typedRouter.use()
is ran just after the request is decoded but
before it is validated, even on checked routes. It'll have access to req.decoded
in
the same way that unchecked routes do.
Other than what is documented above, a wrapped router should behave like a regular
Express one, so things like typedRouter.use()
should behave the same.
FAQs
Implement an HTTP specification with Express
The npm package @api-ts/typed-express-router receives a total of 16,313 weekly downloads. As such, @api-ts/typed-express-router popularity was classified as popular.
We found that @api-ts/typed-express-router demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.