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

fastify-node-config

v1.0.0

Published

Plugin to help integrate thie node-config library with Fastify

Downloads

9

Readme

fastify-node-config

NPM Version

A Fastify plugin to expose configuration values created via node-config on a fastify instance. Provides optional validation via https://ajv.js.org/. Useful if you prefer using node-config for organizing and setting up your application's configuration but would like the values to be accessible in your application similar to @fastify/env.

Install

If you are using this library it is assumed you already are or are intended to use node-config. Regardless of the situation, however, make sure to install node-config as it is peer dependency of this plugin.

:exclamation: note that node-config uses the package name config

Yarn

yarn add fastify-node-config config 
# Install fastify-node-config and node-config dependencies

NPM

npm install fastify-node-config config
# Install fastify-node-config and node-config dependencies

Usage

All examples assume that you have already setup configuration files that are compatible with node-config. See the node-config documentation for details on how to do so. If you are coming here directly, you may wish to consider a simpler setup with @fastify/env and an .env file if you do not need the the additional features or options provided.

For the next two examples, one can assume a json file exists in config/default.json, though any equivalent node-config format can be used so long as it is similar.

{
  "PORT": 3000
}

CommonJS

const fastify = require('fastify')()
const fastifyNodeConfig = require('fastify-node-config')


const schema = {
  type: 'object',
  required: [ 'PORT' ],
  properties: {
    PORT: {
      type: 'string',
    }
  }
}

// both parameters are optional
const options = {
  schema: schema, 
  safe: true, 
}

fastify
  .register(fastifyNodeConfig, options)
  .ready((err) => {
    if (err) console.error(err)

    console.log(fastify.config) 
    //prints config loaded via node-config
  })

ESM

import Fastify from 'fastify';
import fastifyNodeConfig from 'fastify-node-config';

const fastify = Fastify();

const schema = {
  type: 'object',
  required: [ 'PORT' ],
  properties: {
    PORT: {
      type: 'string',
    }
  }
}

// both parameters are optional
const options = {
  schema: schema, 
  safe: true, 
}

fastify
  .register(fastifyNodeConfig, options)
  .ready((err) => {
    if (err) console.error(err)

    console.log(fastify.config) 
    //prints config loaded via node-config
  })

Typescript

import type { JSONSchemaType } from 'ajv';
import Fastify from 'fastify';
import fastifyNodeConfig from 'fastify-node-config';

export interface AppConfig {
  db: {
    host: string;
    port: number;
    name: string;
  };
  server: {
    port: number;
  };
  log: {
    level: string;
    file: string;
  };
}

export const schema: JSONSchemaType<AppConfig> = {
  type: 'object',
  properties: {
    db: {
      type: 'object',
      properties: {
        host: { type: 'string' },
        port: { type: 'number' },
        name: { type: 'string' },
      },
      required: ['host', 'port', 'name'],
    },
    server: {
      type: 'object',
      properties: {
        port: { type: 'number' },
      },
      required: ['port'],
    },
    log: {
      type: 'object',
      properties: {
        level: { type: 'string' },
        file: { type: 'string' },
      },
      required: ['level', 'file'],
    },
  },
  required: ['db', 'server', 'log'],
};

const options = {
  schema: schema, 
  safe: true, 
}

fastify
  .register(fastifyNodeConfig, options)
  .ready((err) => {
    if (err) console.error(err)

    console.log(fastify.config) 
    //prints config loaded via node-config
  })

//In order to have typing for the fastify instance, add a declaration with the types for your configuration:

declare module 'fastify' {
  interface FastifyInstance {
    config: AppConfig 
  }
}

Options

Two optional parameters can be set when registering fastify-node-config: schema and safe.

Schema

Schema is a JSONSchema for validating your configuration values. If validation fails an exception is thrown. This is useful for ensuring that the values you are loading via node-config align with the schema and typings in your application. Generally you will want to allow this to be a fatal exception in your application and it is highly recommended.

Safe

A second parameter safe when true will cause an exception to occur when trying to access a non-existant property in your configuration. Note that nested property chains that are not defined will follow normal semantics with accessing undefined properties. For example

type AppConfig = {
  db :{
    server: string;
    port: number;
}

//...

fastify.config.db.query // throws error on safe is true, will be null when safe is false
fastify.config.db.query.find // TypeError when safe is false

Notes

This library wraps around the config.get functionality core to node-config and as such, if the underlying config, however it may occur, mutates the underlying config, a runtime error would occur as access to the config decorator on the fastify instance internally will call config.has to ensure that it is a valid configuration entry.

Further as this is for the most part a pass through, you should be able utilize any of the conventions and formats present in node-config without any limitations.

The schema does not need to reflect the entire structure of your config, it need merely conform to it. Properties defined in config will still be accessible even if they are not explicitly setup. For example a configuration json such as:

{
  "PORT": "3000",
  "DEBUG": "false"
}

will still allow reaching fastify.config.DEBUG even if your schema is similar to the examples.