1.0.0 • Published 4 years ago

env.gql v1.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
4 years ago

env.gql

Node.js CI npm version TypeScript Compatible

Use GraphQL Type Definitions To Validate process.env

$ npm i env.gql

Examples

This library does not modify process.env directly.

Motivation

Fed up of not knowing what config to pass to a server? Use GraphQL to explain and validate your environment variables. Never see cannot connect to 'undefined' again 🎉

Inspiration

  1. GraphQL
  2. dotenv
  3. env-var

Example

process.env.PORT will be casted to a number, process.env.DEV will be casted to a boolean.

const envGQL = require("env.gql");

const typeDefs = `
    input Config {
        PORT: Number!
        URL: String!
        SECRET: String!
        DEV: Boolean!
    }
`;

const config = envGQL({ typeDefs });

Using .gql file

The idiomatic file convention is .env.gql

const path = require("path");
const envGQL = require("env.gql");

const typeDefsPath = path.join(__dirname, "./.env.gql");
const config = envGQL({ typeDefs: typeDefsPath });

Using directives

Using graphql-constraint-directive

const envGQL = require("env.gql");
const { constraintDirective, constraintDirectiveTypeDefs } = require('graphql-constraint-directive')

const typeDefs = `
    input Config {
        PORT: Number 
        URL: String @constraint(format: "uri")
        SECRET: String 
    }

    ${constraintDirectiveTypeDefs}
`;

const config = envGQL({ 
    typeDefs,
    schemaTransforms: [constraintDirective()]
});

Override

Use to validate not just process.env

const envGQL = require("env.gql");

const typeDefs = `
    input Config {
        PORT: Number
        URL: String
        SECRET: String
    }
`;

const config = envGQL({ 
    typeDefs,
    override: {
        PORT: 4000, 
        URL: "http://github.com",
        SECRET: "supersecret"
    }
});

graphql-tag

const envGQL = require("env.gql");
const gql = require("graphql-tag");

const typeDefs = gql`
  input Config {
    PORT: Int
    URL: String
    SECRET: String
  }
`;

const config = envGQL({
  typeDefs: typeDefs,
});

TypeScript

import envGQL from "env.gql";

const typeDefs = `
  input Config {
    PORT: Int
    URL: String
    SECRET: String
  }
`;

interface Config {
  PORT: number;
  URL: string;
  SECRET: string;
}

const config = envGQL<Config>({
  typeDefs,
});

Defaults

const typeDefs = `
  input Config {
    PORT: Int = 123
    URL: String = "http://github.com"
    SECRET: String = "supersecret"
    DEV: Boolean = false
  }
`;

const config = envGQL({
  typeDefs: typeDefs,
});

typeof config.PORT === "number"
typeof config.URL === "string"
typeof config.SECRET === "string"
typeof config.DEV === "boolean"

Required

Use GraphQL ! symbol

const typeDefs = `
  input Config {
    PORT: Int! # Required
    URL: String
    SECRET: String
    DEV: Boolean
  }
`;

const config = envGQL({
  typeDefs: typeDefs,
});