JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1344
  • Score
    100M100P100Q97672F
  • License MIT

The hapi utility toy chest

Package Exports

  • toys

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (toys) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

toys

The hapi utility toy chest

Build Status Coverage Status

Lead Maintainer - Devin Ivy

Usage

See also the API Reference

Toys is a collection of utilities made to reduce common boilerplate in hapi v17+ projects, aid usage of events and streams in async functions (e.g. handlers and server methods), and provide versions of widely-used utilities from Hoek optimized to perform well in hot code paths such as route handlers.

Below is an example featuring Toys.auth.strategy(), Toys.reacher(), and Toys.withRouteDefaults(). The API Reference is also filled with examples.

const Hapi = require('@hapi/hapi');
const Boom = require('@hapi/boom');
const Toys = require('toys');

(async () => {

    const server = Hapi.server();

    // Make a one-off auth strategy for testing
    Toys.auth.strategy(server, 'name-from-param', (request, h) => {

        // Yes, perhaps not the most secure
        const { username } = request.params;

        if (!username) {
            throw Boom.unauthorized(null, 'Custom');
        }

        return h.authenticated({ credentials: { user: { name: username } } });
    });

    // Make function to efficiently index into a request to grab an authed user's name
    const grabAuthedUsername = Toys.reacher('auth.credentials.user.name');

    // Default all route methods to "get", unless otherwise specified
    const defaultToGet = Toys.withRouteDefaults({ method: 'get' });

    server.route(
        defaultToGet([
            {
                method: 'post',
                path: '/',
                handler: (request) => {

                    return { posted: true };
                }
            },
            {   // Look ma, my method is defaulting to "get"!
                path: '/as/{username}',
                options: {
                    auth: 'name-from-param', // Here's our simple auth strategy
                    handler: (request) => {

                        // grabAuthedUsername() is designed to be quick
                        const username = grabAuthedUsername(request);

                        return { username };
                    }
                }
            }
        ])
    );

    await server.start();

    console.log(`Now, go forth and ${server.info.uri}/as/your-name`);
})();