@routup/body
TypeScript icon, indicating that this package has built-in type declarations

2.3.0 • Public • Published

@routup/body

npm version main codecov Known Vulnerabilities Conventional Commits

This is a plugin for reading and parsing the request payload.

Table of Contents

Installation

npm install @routup/body --save

Documentation

To read the docs, visit https://routup.net

Usage

For standard use, the package is installed as a plugin, as shown below.

import { createServer } from 'node:http';
import { 
    createNodeDispatcher,
    coreHandler,
    Router, 
    send
} from 'routup';
import { body, useRequestBody } from '@routup/body';

const router = new Router();
// This will parse requests with Content-Type:
// application/json
// application/x-www-form-urlencoded
router.install(body());

router.get('/', coreHandler((req, res) => {
    const body = useRequestBody(req);
    console.log(body);
    // ...
}));


const server = createServer(createNodeDispatcher(router));
server.listen(3000)

Options

The plugin accepts an object as input parameter to modify the default behaviour.

json

To parse application/json input data, enable the json handler.

  • Type: Options | boolean
  • Default: true
router.use(body({
    json: {
        limit: '100kb'
    }
}));

urlEncoded

To parse application/x-www-form-urlencoded input data, enable the url-encoded handler.

  • Type: Options | boolean
  • Default: true
router.use(body({
    urlEncoded: {
        extended: false
    }
}));

raw

To parse any input data as Buffer, enable the raw handler.

  • Type: Options | boolean
  • Default: false
router.use(body({
    raw: {
        inflate: false
    }
}));

text

To parse any input data as string, enable the text handler.

  • Type: Options | boolean
  • Default: false
router.use(body({
    raw: {
        inflate: false
    }
}));

Helpers

setRequestBody

This function sets the parsed request body/payload for the current request. This method should be implemented by a router middleware/plugin.

declare function setRequestBody(
    req: Request,
    key: string,
    value: unknown
) : void;

declare function setRequestBody(
    req: Request,
    record: Record<string, any>
) : void;

useRequestBody

This function returns the parsed request payload.

declare function useRequestBody(
    req: Request
) : Record<string, any>;

declare function useRequestBody(
    req: Request, key: string
) : any | undefined;

Credits

This library is currently based on the body-parser library, but this might change in the near future.

License

Made with 💚

Published under MIT License.

Package Sidebar

Install

npm i @routup/body

Weekly Downloads

127

Version

2.3.0

License

MIT

Unpacked Size

34 kB

Total Files

27

Last publish

Collaborators

  • tada5hi