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

tyranid-openapi

v0.5.20

Published

Open API spec and express app generator for tyranid

Downloads

33

Readme

OpenAPI / Swagger spec generator for Tyranid

npm version Build Status codecov

This project provides a way to generate a complete + valid openAPI spec by adding schema annotations to your tyranid models.

NOTE: this library only creates the spec itself, implementation is left to the app code for now (but might be a good feature for this library later on).

Contents

Schema Options

There are various options for configuring how the tyranid models appear to the public api. You can see the CollectionSchemaOptions (specified in as an object on the schema definition named openAPI) and FieldSchemaOptions (specified on specific fields in the schema as a property named openAPI) interfaces in ./src/interfaces.ts.

Generating the Spec

Once you have specified some collections to be exposed by annotating the schemas, you can generate the actual spec file as follows...

import { Tyr } from 'tyranid';
import { spec } from 'tyranid-openapi';
import { writeFileSync } from 'fs';
import { join } from 'path';

// async function for bootstrap
(async () => {
  // bootstrapping without db to just get schema graph
  await Tyr.config({
    validate: [{ glob: join(__dirname, './models/*.js') }]
  });

  // generate yaml openAPI spec string
  const specString = spec(Tyr, { yaml: true });

  // write out to file
  writeFileSync(join(__dirname, './my-api.yaml'), specString);
})().catch(console.error);

Exposing a single collection

The most basic way to expose a collection to the public api is by setting the openAPI flag to true, and marking a few properties to show. For example...

import { Tyr } from 'tyranid';

export default new Tyr.Collection({
  id: 't01',
  name: 'metric',
  dbName: 'metrics',

  // this indicates that we want GET/PUT/POST/DELETE endpoints
  // for `/metrics` and  `/metrics/{_id}`. Additionally, `read:metrics` and
  // `write:metrics` scopes will be created.
  openAPI: true,

  fields: {
    _id: { is: 'mongoid' },
    organizationId: { is: 'mongoid' },

    // here we mark that we want to expose this field to the api
    // also, since it is marked `required`, api users will recieve
    // an error if they do not POST/PUT data that includes it.
    name: { is: 'string', openAPI: true, required: true }
  }
});

"Parent" collections

Some times there might be several collections which you want to have fall under a single set of permission scopes. Additionally, you want the api url to be nested.

For example, say we have a metrics collection containing metadata about individual metrics (like usage analytics or budget numbers) as well as a metricObservations collection which contains the actual time series. To keep metricObservations in the same permission scope as metrics, we would add the following annotation...

export default new Tyr.Collection({
  id: 'mtg',
  name: 'metricTarget',
  dbName: 'metricTargets',
  openAPI: {
    // define the parent collection, this means that
    // the api paths will be nested under metrics, so
    // `/metrics/{_id}/observations`, `/metrics/{_id}/observations/{_id}`
    parent: 'metric',
    // here we say that we want to use the permission scopes
    // (`read:metrics`/`write:metrics`) for this collection
    useParentScope: true
  },
  fields: {
    _id: { is: 'mongoid' },
    metricId: { link: 'metric', openAPI: true },
    date: { is: 'date', openAPI: true },
    value: { is: 'double', openAPI: true },
    organizationId: { is: 'mongoid' },
    excludeProperty: { is: 'string' },
    type: {
      link: 'metricTargetType',
      openAPI: true
    }
  }
});

Renaming and Restricting certain properties

If there are certain properties that are automatically generated by the database (like timestamps), you can mark them to only be returned / accepted from read endpoints. Additionally, you can provide different public names for properties...

import { Tyr } from 'tyranid';

export default new Tyr.Collection({
  id: 't01',
  name: 'metric',
  dbName: 'metrics',
  openAPI: true,
  fields: {
    _id: { is: 'mongoid' },
    organizationId: { is: 'mongoid' },
    name: { is: 'string', openAPI: true, required: true },
    privateNamedProperty: {
      is: 'string',
      openAPI: {
        // only allow this property in results of GET / PUT / POST,
        // do not allow it to be sent as part of an update (PUT/POST)
        include: 'read',
        // in the spec, this property will be called `publicName`
        name: 'publicName'
      }
    }
  }
});

Partitioning a collection into multiple "virtual" collections

If there is a single database collection which represents several distinct types of data which you wish to expose in different endpoints, you can "partition" the collection...

import { Tyr } from 'tyranid';

export default new Tyr.Collection({
  id: 'i01',
  name: 'item',
  dbName: 'items',
  openAPI: {
    // this will create two new types for the api:  `Plan` + `Task` + `Project`,
    // with `/task`, `/project`, and `/plan` endpoints, etc...
    partition: [
      {
        name: 'plan',
        // here we define a mongodb query to separate the
        // data into their specific partitions
        partialFilterExpression: {
          kind: 'plan'
        }
      },
      {
        name: 'task',
        partialFilterExpression: {
          kind: 'task'
        }
      },
      {
        name: 'project',
        partialFilterExpression: {
          kind: 'project'
        }
      }
    ]
  },
  fields: {
    _id: { is: 'mongoid' },
    organizationId: { is: 'mongoid' },
    name: { is: 'string', openAPI: true, required: true },
    kind: { is: 'string' },
    planField: {
      is: 'string',
      openAPI: {
        // we might want some fields to only appear on
        // certain partitions (can also be an array of partitions)
        partition: 'plan'
      }
    },
    taskField: {
      is: 'string',
      openAPI: {
        partition: 'task'
      }
    },
    nestedPartitionField: {
      is: 'object',
      fields: {
        innerPlanOrProjectField: {
          is: 'string',
          openAPI: {
            partition: ['plan', 'project'],
            name: 'renamedPartitionField'
          }
        },
        innerTaskField: { is: 'string', openAPI: { partition: 'task' } }
      }
    }
  }
});