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

mongo-type-gen

v1.1.0

Published

A type and sdl generator for MongoDB jsonSchema

Downloads

16

Readme

release NPM Version NPM Downloads BundleSize Patreon

mongo-type-gen is a lib for unifing your types. Define once, reuse everywhere!

  • Simple: Short mtg command allows for easy generating, uploading, and downloading of types.
  • Performant: Lightweight with very few deps and a small bundle size.

Takes a collection definition, ie **.collection.js;

module.exports {
  indexes: [
    {
      key: { name: 1 },
      unique: true,
    },
  ],
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      properties: {
        gpa: {
          bsonType: ['double'],
          description: "'gpa' must be a double if field exists",
        },
        name: {
          bsonType: 'string',
          description: "'name' must be a string and is required",
        },
        year: {
          bsonType: 'int',
          description: "'year' must be an integer in [  2017,  3017  ] and is required",
          maximum: 3017,
          minimum: 2017,
        },
      },
      required: ['major', 'name', 'year'],
      title: 'Student Object Validation',
    },
  },
};

And generates a mongo.types.ts and mongo.sdls.ts typing files for your Typescript types and GraphQL SDLs;

/* This file is generated by mongo-type-gen.  Do not edit */

import { ObjectId } from 'mongodb';

export enum CollectionEnum {
  students = 'students',
}

export type StudentDoc = {
  gpa?: number;
  name: string;
  year: number;
};
/* This file is generated by mongo-type-gen.  Do not edit */

import { gql } from 'graphql-tag';

export default gql`
  enum CollectionEnum {
    students
  }

  type StudentDoc {
    gpa: Float
    name: String!
    year: Int!
  }
`;

Table of Contents

Motivation

Working with typescript can involve some busy work. Creating all the different types associated with your data by hand is tedious and time consuming. From GraphQL SDLs, to Typescript types, to Mongo JSON schemas or Mongoose Schemas. This takes time and introduces tech debt if data is added or modified.

Let's dry this up and only define our types once. Let mongo-type-gen handle the busy work of producing the different types needed for your GraphQL app writen in Typescript.

First, let's identify the best source for types. What syntax allows us to be the most expressive 🤔. This is where Mongo's `$jsonSchema`` validators come into play. They allow for expression of meta data that cannot be expressed in Typescript, GraphQL, or Mongoose alone. This lib uses validators as the source.

Whether you have your validators defined in your project or they live in MongoDB, we'll grab em' and generate your types and SDLs.

Usage

To get started, add the lib to your project. You'll only need it for local dev so install it as a dev dep.

npm i -D mongo-type-gen

Then create some ease-of-use scripts in your package.json.

{
  "scripts": {
    "start": "mtg -w & ts-node-dev ./src/index.ts"
  }
}

With mongo-type-gen, you'll need Mongo JSONSchema flavor validators. You can either define these in the project and ref them in a mtg.config.ts config file or have mtg download them from mongo.

To see this in action, create a mtg.config.js config file.

import configMtg from 'mongo-type-gen';

export default configMtg({
  db: 'mongo-type-gen', // name of your db, required
  input: '**/*.collection.*s', // glob pattern of your collection files, if not present mtg will fetch your collection from Mongo
  output: {
    collections: 'examples/collections', // output directory to place your collection files if mtg fetches them from Mongo
    sdls: 'examples/sdls', // output dir to place your typescript types
    types: 'examples/types', // output dir to place your SDLs
  },
  uri: 'mongodb://localhost:27017',
});

This let's mtg learn where it should download or upload your collections and where it should place your types.

There is also a watcher available by passing -w so any changes you make to your collection's is reflected in your types and Mongo.

When downloading your collection's from Mongo, mtg will add an isGenerated boolean field to the data. This lets mtg know how to manage your collection data. If the bool is true, mtg will not upload your data to Mongo as it is expecting Mongo to be the source of truth. This is useful for apps that need Mongo's types but are not responsibile to setting validators and indexes. You can switch the role by simiply removing the isGenerated flag from the data.

Validators

Curious about validators? Check out Mongo's docs. Validators are awesome! https://www.mongodb.com/docs/upcoming/core/schema-validation/#schema-validation