npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

servaljs

v1.2.0

Published

ServalJS is a toolset for FastifyJS

Downloads

30

Readme

ServalJS

NPM Version

Introduction

ServalJS is not a framework but rather a utility set for FastifyJS, written in TypeScript. It was developed to provide more structured and organized code on the backend.

Table of contents

Installation

npm i --save fastify servaljs @fastify/middie

Creating Serval application

To create Fastify application powered by Serval tool set, createServal function is used. This is also the main entry point for the application which is used to configure it. Application configuration is pretty simple. There are 4 important properties in configuration object (see Snippet 1):

  • server.port - Specify the port on which Express server will be available,
  • controllers - Array of controller objects which will be mounted in order,
  • middleware - Array of middleware object which will be mounted in order,
  • modules - Array of module objects which will be mounted in order,
const app = createServal({
  server: {
    port: 7000,
  },
  modules: [
    /* List of modules */
  ],
  controllers: [
    /* List of controllers */
  ],
  middleware: [
    /* Middleware list */
  ],
});

Snippet 1 - Create a Serval application.

This will be explained in more detail.

  • First step is mounting modules. They are mounded in FIFO order and once 1 module is mounted, it will trigger a callback which will mount the next module, and so on.
  • Next step is mounting middleware objects.
  • In next step, all controller objects will be mounted in FIFO order.
  • With all above steps completed successfully, onReady function will be called, HTTP server will be started and it will print message like one shown below:
Serval - Started Successfully
-------------------------------------
PORT: 1280
PID: 24720
TTS: 0.007s

Controller

Most important tools for creating REST APIs are tools for connecting HTTP requests with some business logic, doing a required work and creating a response. This is as easy as creating an HTTP route handler for specified method. In pure Fastify application this could be done like shown in Snippet 2.

fastify.get('/user', (request, replay) => {
  // Get user from the database
  // ...
  return user;
});

Snippet 2 - Creating an endpoint using Fastify

This is all very nice but writing a code this way can be messy and organizing it can be a challenge. Because of this, abstracts like Controller, Controller method and Middleware exist in the Serval tool set. In this section, Controller abstract will be covered.

Controller is an abstraction which provides clean and unified way for creating a group of REST endpoints. Controller object is created by calling createController function which accepts configuration object as an argument. Controller by itself if just a "placeholder" and does not hold any complex logic. To implement a logic, and to add REST endpoints, Controller method is used.

By using the Serval Controller approach, code from Snippet 2 can be rewritten like shown in Snippet 3.

const UserController = createController({
  name: 'User',
  path: '/user',
  methods() {
    return {
      getUser: createControllerMethod<void, User>({
        type: 'get',
        async handler() {
          // Get user from the database
          // ...
          return user;
        },
      }),
    };
  },
});

Snippet 3 - Create an endpoint using the Serval controller/method approach.

Much more code is written in Snippet 3 compared to 2, so why is this better? Second example provides structure, consistency (which is not easy to spot on such a short example) and unified way to create REST endpoints. This means that navigation in project is much quicker, and it is easier to understand what is the end result of each endpoint. In addition to that, return type of the method can be specified.

Pre request handler

It is a method inside of a Controller Method configuration object. It is executed before each required to specified route and output from it is piped to handler method. For example, you can create a pre request handler which will convert a first letter of a request parameter in upper-case like shown in Snippet 5.

const MyController = createController<{ baseMessage: string }>({
  name: 'My controller',
  path: '/hello',
  methods() {
    return {
      world: createControllerMethod<{ name: string }, { message: string }>({
        path: '/:name',
        type: 'get',
        async preRequestHandler({ request }) {
          const params = request.params as { name: string };
          return {
            name:
              params.name.substring(0, 1).toUpperCase +
              params.name.substring(1).toLowerCase(),
          };
        },
        async handler({ name }) {
          return {
            message: `Hello ${name}!`,
          };
        },
      }),
    };
  },
});

Snippet 4 - Controller method pre request handler

Again, example from Snippet 4 is trivial but it illustrates how pre request handler is used. As it can be seen, pre request handler functions like a middleware but only for specific route. It is useful when different routes use different mechanisms for security and resource protection.

Middleware

Middleware is similar to a controller, but it is usually used to transform incoming or outgoing data in some shape or form. Because of this, middleware is triggered for all methods on all routes which are starting with a specified path.

Like the createController function, createMiddleware function returns the Middleware object which is used in the Serval configuration object in the middleware array property. Example for creating a middleware object is shown in Snippet 6.

createMiddleware({
  name: 'Test middleware',
  path: '/test',
  handler() {
    return async () => {
      // Middleware logic.
    };
  },
});

Snippet 5 - Creating a simple middleware object.

It is important to know that handler method can be asynchronous and will be called only once when the middleware is mounted. So before returning a request handler function, setup of the middleware can be done.

Modules

Module is the core abstract in the Serval which allows external code to access the pipe. Modules are passed to the configuration object in modules array.