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

swagger-codegen

v0.1.1

Published

Code generation for Swagger based API's.

Downloads

2,790

Readme

swagger-codegen

Travis-CI Build Prod Dependencies Dev Dependencies Coverage Status npm version

Stats Downloads

Code generation for Swagger based API's. Supports NodeJS 4.x+.

Overview

A code generation module for simplifying the consumption of Swagger services. Allows generation of content based on groupings of custom attributes on paths and per-entity/definition.

The code is intended to be as pluggable as reasonably practical, and pull requests to support additional features are very, very welcome.

Gulp Task

This module is leveraged in the gulp-swagger-codegen module, but can be used independently for generating code at runtime.

Usage

The code generation can be invoked with:

const codegen = require('swagger-codegen');

// Synchonrous method
codegen({
  // Parse your YAML or JSON and load here
  swagger: yourSwaggerObjectHere,

  // Templates that run per #/definition
  perDefinition: {
    // Substitute for your own handlebars template
    // and generate as many as you want.
    './path/to/def-template.hbs': {
      target: './target-folder',
      extension: '.js', // Default
      /* Add your own options for templates here */
    }
  },

  // Templates that run per grouping of 
  // path attributes
  perPath: {
    // Substitute for your own handlebars template
    // and generate as many as you want.
    './path/to/def-template.hbs': {
      groupBy: 'x-swagger-router-controller',
      target: './controllers',
      extension: '.js', // Default
      operations: ['get', 'put', 'post', 'delete'], // Default
      /* Add your own options for templates here */
    }
  }
});

Templating

Data Context

Each template is provided with a collection of objects to use when generating code. This collection varies based on the type of template being processed and there are some fields common across all types. This object is passed as a map to the template engine as the root-object.

Common Fields

The following fields are common for all template types:

  • model: The complete parsed Swagger content (JSON/object structure)
  • definitionMap: A name/definition map of all known definitions in Swaggerfile.
  • options: The options object passed into the code-generation function.

Per-Definition Templates

Generated per entity/#definition in the Swaggerfile, fields are:

  • definition: The current definition being processed.

Per-Path Templates

Fields are:

  • groupKey: The value of the groupBy attribute that this file represents.
  • members: The map of operations from the swaggerfile that link to this file.
  • fileName: The physical file-name this perPath template will use.

Handlebars Template Helper Functions

Registering Your Own

You can register your own handlebars helper functions by adding a top-level configuration property called helpers and assigning the functions as key-values. The key will be the exact block-helper name and the value must be the helper function itself.

arrayContains

Does the array contain an item?

  {{#arrayContains arrayProp value}}
    // Template if value is in array
  {{else}}
    // Template if value is not in array
  {{/arrayContains}}

compare

Perform a comparison operation.

  {{#compare leftVal operand rightVal}}
    // Template if leftVal op rightVal true
  {{else}}
    // False template
  {{/compare}}

Supported operands are ==, ===, !=, >, >=, <, <= and typeof

lowercase

Converts a block to lowercase.

{{#lowercase}}MAKE ME LOWERCASE{{/lowercase}}

lowerFirst

Makes the first character of a block lowercase, but leaves the rest of the block untouched.

{{#lowerFirst}}MAKES FIRST M LOWERCASE{{/lowerFirst}}

property

Property name complication helper.

{{#property someProp "property-name-with-bad-characters" "resultName"}}
  This scope will be `someProp` but with an extra sub-property of resultName
{{else}
  This scope will be returned if property-name-with-bad-characters does not exist
{[/property

This is used primarily because handlebars does not natively seem to permit invalid characters in variable names. Some of the extended swaggerfile attributes are prefixed with x- and so to reason about them in templates, you'll need this.

uppercase

Converts a block to uppercase.

{{#uppercase}}i want to be tall{{/uppercase}}

upperFirst

Makes the first character of a block uppercas, but leaves the rest of the block untouched.

{{#upperFirst}}mAKES THE FIRST m UPPERCASE{{/upperFirst}}

withDef

Creates a child scope using the specified definition as the context:

{{#withDef defReferencePath}}
  // Generate a sub-section that relates to a definition.
{{/withDef}}

This allows creation of cross-entity relations/nesting, and is shown being used in the included ES6 definition template.

Additional options

In addition to the swagger, perPath and perDefinition options, you can pass through the following values. All of the below have default implementations that can be used:

  • definitionMapper | (model) -> map
    • Compute a map/array of definition names to definitions. Allows you to selectively filter or substitute definitions during code generation.
  • failureHandler | (err) -> action
    • Run a command when an error occurs. Processing of the entire code generation task is abandoned. Default implementation exits the process with an error code of -1 and writes the message/stack trace to stdout.
  • templateEngine | (taskOptions) --> engine
    • Function to create an instance of the template engine. Recieves the entire task options as an input. There is a default .helpers property that contains the well-known helper functions.
  • templateLoader | (templater) -> templateLoader
    • Function that generates types to handle template loading. Default implementation is a class that reads from disk. Returned object must have a .loadTemplate object that returns a template-function.
  • textEncoding | (string)
    • Default text encoding when loading templates from files. Default is utf8

Custom Template Engines

To use a custom template engine besides handlebars:

  • Create a function such as: function createTemplateEngine(opts) { return new MyTemplateEngine(); }

  • Pass the template loader as: codegen({ ... task options ...,

      templateEngine: createTemplateEngine
    });

Note that 'MyTemplateEngineType' instances must have a .loadTemplate(content) implementation, where content is the loaded text of the template file. The .loadTemplate operation must return a function such as:

// Normally called by the swagger-codegen
const engine = new MyTemplateEngine();

// Must have a .loadTemplate(string) method
const templateInstance = engine.loadTemplate(someTextContent);

// Must be a function that takes context data
const output = templateInstance(contextData);

Where contextData is the template-type specific context data, as described in the templating context data section. This model allows most pluggable template engines to be used in lieu of the default handlebars.

Licence

This code is MIT licensed and comes without any warranties. Please see the LICENSE file for specifics.