Code Monkey home page Code Monkey logo

serverless-models-plugin's Introduction

serverless-models-plugin

serverless

This plugin adds the missing model support to Serverless 0.5.x.

Overview

The plugin lets you define your models within your project. Models are important as soon as you play around with the mobile SDK's generated by AWS Gateway. They define the typed results or inputs of your API definition and are mapped to classes in the SDK's. One advantage is, that if a model is used in more than one endpoints of your API, or a model references other models for its sub-objects, the generated SDK uses exactly the same class definition instance throughout the SDK.

As soon as you reference them within your endpoint definitions and deploy the endpiont, the needed models are uploaded to API Gateway. If the model already exists, the definition is updated.

Installation

  1. Install the plugin module npm install serverless-models-plugin will install the latest version of the plugin.

    If you want to debug, you also can reference the source repository at a specific version or branch with npm install https://github.com/HyperBrain/serverless-models-plugin#<tag or branch name>

  2. Activate the plugin in your Serverless project Add serverless-models-plugin to the plugins array in your s-project.json.

    {
      "name": "testp1",
      "custom": {},
      "plugins": [
        "serverless-models-plugin"
      ]
    }
    

Usage

Model definition

Within anywhere of your Serverless project space you can create a s-models.json or s-models.yaml (both formats are supported). Within this files define your models ( you can $ref models between s-models files).

functions/
└── function1
    ├── event.json
    ├── handler.js
    ├── s-function.json
    └── s-models.json

Example (YAML)

myModelOne:
  '$schema': 'http://json-schema.org/draft-04/schema#'
  type: object
  properties:
    myProp:
      type: string
    myProp2:
      type: number
myModelTwo:
  '$schema': 'http://json-schema.org/draft-04/schema#'
  type: array
  items:
    type: string

Example (JSON)

{
  "myModelOne": {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "properties": {
      "myProp": {
        "type": "string"
      },
      "myProp2": {
        "type": "number"
      }
    }
  },
  "myModelTwo": {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "array",
    "items": {
      "type": "string"
    }
  }
}

Model references

Models can reference other models. You can do this easily by adding $ref properties that refer to another defined model. The plugin will take care of including and deploying referenced models properly.

Example (YAML)

myModelOne:
  '$schema': 'http://json-schema.org/draft-04/schema#'
  type: object
  properties:
    myProp:
      type: string
    myProp2:
      type: number
myModelTwo:
  '$schema': 'http://json-schema.org/draft-04/schema#'
  type: array
  items:
    $ref: myModelOne

Example (JSON)

{
  "myModelOne": {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "properties": {
      "myProp": {
        "type": "string"
      },
      "myProp2": {
        "type": "number"
      }
    }
  },
  "myModelTwo": {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "array",
    "items": {
      "$ref": "myModelOne"
    }
  }
}

Using models in endpoints

If you want to declare a response (output) or request (input) model for an endpoint, you just have to add it to your s-function.json accordingly (see requestModels and responseModels properties):

{
  "name": "testfct2",
  "runtime": "nodejs",
  "description": "Serverless Lambda function for project: testp1",
  "customName": false,
  "customRole": false,
  "handler": "handler.handler",
  "timeout": 6,
  "memorySize": 1024,
  "authorizer": {},
  "custom": {
    "excludePatterns": []
  },
  "endpoints": [
    {
      "path": "testfct2",
      "method": "GET",
      "type": "AWS",
      "authorizationType": "none",
      "authorizerFunction": false,
      "apiKeyRequired": false,
      "requestParameters": {},
      "requestModels": {
        "application/json": "myModelOne"
      },
      "requestTemplates": {
        "application/json": ""
      },
      "responses": {
        "400": {
          "statusCode": "400"
        },
        "default": {
          "statusCode": "200",
          "responseParameters": {},
          "responseModels": {
            "application/json": "myModelTwo"
          },
          "responseTemplates": {
            "application/json": ""
          }
        }
      }
    }
  ],
  "events": [],
  "environment": {
    "SERVERLESS_PROJECT": "${project}",
    "SERVERLESS_STAGE": "${stage}",
    "SERVERLESS_REGION": "${region}"
  },
  "vpc": {
    "securityGroupIds": [],
    "subnetIds": []
  }
}

Helper commands

The plugin also adds some new commands to Serverless: sls models XXXXXX

list

Lists the defined model names

show

Shows specified model definitions as JSON or YAML. Usage: sls models show <model names> [--format json|yaml]

more to come

Releases

1.1.0

  • s-models.[yaml|json] files are now used throughout the project hierarchy and merged on deploy.

1.0.0

  • Initial release

1.0.1

  • Documentation enhancements: issues #1, #2

1.1.0

  • Documentation enhancements: issues #9
  • Added support for placing s-models within anywhere of the project's space

serverless-models-plugin's People

Contributors

hyperbrain avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

serverless-models-plugin's Issues

Automatically add dependency to package.json

When using other plugins the dependencies in package.json are added. This is not the case for the serverless-models-plugin. When transferring project to other machine (i.e. a build server) the plugins are not automatically installed with npm install

Is this an error at my side? Otherwise this might be a good add?

'sls models show' not working

I am getting the following error:

xxx-MacBook-Pro:serverless-famepick xxx$ sls models show
/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:61
        fn = function () { throw arg; };
                           ^

ServerlessError: Command not found.  Enter "serverless help" to see all available commands.
    at new ServerlessError (/usr/local/lib/node_modules/serverless/lib/Error.js:17:11)
    at Serverless.command (/usr/local/lib/node_modules/serverless/lib/Serverless.js:360:31)
    at /usr/local/lib/node_modules/serverless/bin/serverless:19:16
    at tryOnImmediate (timers.js:534:15)
    at processImmediate [as _immediateCallback] (timers.js:514:5)
From previous event:
    at Object.<anonymous> (/usr/local/lib/node_modules/serverless/bin/serverless:18:4)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:146:18)
    at node.js:404:3

Questions about Swagger compatibility and implications.

I found this project during my initial research on practical Serverless implementation and was wondering if any thought about compatibility with Swagger and Swagger specifications has went into it, or if the author is planning on implementing anything of that nature in the future.

Specifically:
  • Is it possible to pull or push model information to and from a Swagger specification file?
  • Has this project been tested, to any degree, with the Swagger export plugin for Serverless?
  • If so, is it known whether or not the two plugins are mutually exclusive?

I would not mind bringing myself and my team to the effort, but I wouldn't want to do that if we're going to be way-off-track from the plugin's core ideals and objectives.

Thanks,

updating s-project.json

although there is generic text at serverless.com it would be nice to have a section on adding this plugin to. I guessed wrong with 'serveless-model' and realised my error. If the really-useful server less-models-plugin is one's first plugin one could over look the need to update

In the file s-project.json add the plug to the list of plug-ins. E.g.,

{
"name": "juturnaSLS",
"custom": {},
"plugins": ["serverless-models-plugin"]
}

How to retrieve models/schemas in Lambda/Javascript?

Since API Gateway does not use Models to perform any schema validation of request/response messages (currently at least), Im considering using one of the Javascript JSON-Schema validator implementations for NodeJS to do this myself inside Lambda handler.

In order to do that, validators are requiring schemas and then I need to be able to retrieve the models/schemas from s-models.json file. Is it as easy as just using require() function, or do you suggest another way?

JSON example

In addition to the YAML examples for defining a Model it'd be handy to give a JSON example. One could then see what was required and also where the format differs from that entered directly into API Gateway.

Error 'Model not defined: Empty'

Hyprbrain,

wanted to use your plugin for added model support but when testing I am getting an error:
"POST - registrations: Model not defined: Empty" where I have a sls function named 'registration'.

I defined a model 'registrationModel' in s-models.json (in my project root folder) and referenced to it in my s-function.json like this:

      "requestModels": {
        "application/json": "registrationModel"
      },

sls models list outputs me the model:

$ sls models list
Serverless: registrationModel  

and the sls models show registrationModel gives:

$ sls models show registrationModel
Serverless: 
{
  "registrationModel": {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "properties": {
      "myProp": {
        "type": "string"
      },
      "myProp2": {
        "type": "number"
      }
    }
  }
} 

sls dash deploy --debug gives:

Serverless: Deploying endpoints in "dev" to the following regions: eu-central-1  
Serverless: /   serverless:lib.node_modules.serverless.lib.ProviderAws "dev - eu-central-1": found existing REST API on AWS API Gateway with name: BCOS-Serverless +186ms
  serverless:lib.node_modules.serverless.lib.utils.index Writing file: /Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/_meta/variables/s-variables-dev-eucentral1.json... +3ms
Serverless: |   serverless:lib.node_modules.serverless.lib.ProviderAws "dev - eu-central-1": found existing REST API on AWS API Gateway with name: BCOS-Serverless +168ms
  serverless:lib.node_modules.serverless.lib.utils.index Reading file: /Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/s-models.json... +9ms
Serverless: Failed to deploy endpoints in "dev" to the following regions:  
Serverless: eu-central-1 ------------------------  
Serverless:   POST - registrations: Model not defined: Empty  
  serverless:lib.node_modules.serverless.lib.actions.EndpointDeploy ServerlessError: Model not defined: Empty
    at new ServerlessError (/Users/dennisoverbeeke/npm/lib/node_modules/serverless/lib/Error.js:17:11)
    at /Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/lib/actions/ModelsDeploy.js:100:45
    at tryCatcher (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:502:31)
    at Promise._settlePromise (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:559:18)
    at Promise._settlePromise0 (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:604:10)
    at Promise._settlePromises (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:683:18)
    at Promise._fulfill (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:628:18)
    at Promise._resolveCallback (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:445:14)
    at Promise._settlePromiseFromHandler (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:514:17)
    at Promise._settlePromise (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:559:18)
    at Promise._settlePromise0 (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:604:10)
    at Promise._settlePromises (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:683:18)
    at Promise._fulfill (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:628:18)
    at MappingPromiseArray.PromiseArray._resolve (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise_array.js:125:19)
    at MappingPromiseArray._filter (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/map.js:123:10)
    at MappingPromiseArray._promiseFulfilled (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/map.js:95:18)
    at MappingPromiseArray.PromiseArray._iterate (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise_array.js:113:31)
    at MappingPromiseArray.init (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise_array.js:77:10)
    at Promise._settlePromise (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:556:21)
    at Promise._settlePromise0 (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:604:10)
    at Promise._settlePromises (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/promise.js:683:18)
    at Async._drainQueue (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/async.js:138:16)
    at Async._drainQueues (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/async.js:148:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/Users/dennisoverbeeke/Documents/Development/BCOS-Serverless/node_modules/serverless-models-plugin/node_modules/bluebird/js/release/async.js:17:14)
    at processImmediate [as _immediateCallback] (timers.js:383:17) +5ms
Serverless:   
Serverless: Run this again with --debug to get more error information...  

Would love to use the plugin but it it not working for me... Did I do something wrong? Or is something not working correctly?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.