Coder Social home page Coder Social logo

node_api_generator's Introduction

Installation

$ npm install -g node-api-generator

Quick Start

Based of the crufty express generator that scaffolds a basic Node API with support for Sequelize ORM The quickest way to get started with express is to install the package globally and run the executable node-api CLI command to generate an application as shown below:

Create the application:

$ node-api my_api

Install dependencies using yarn or npm:

$ npm install
$ yarn install

Run the dummy test included in the scaffold

$ npm test
$ yarn test

Command Line Options

This generator can also be further configured with the following command line flags.

-h, --help          output usage information
-V, --version       output the version number
    --git           add .gitignore
-f, --force         force on non-empty directory

Key dependencies

Sequelize 6 is a promise-based ORM (Object Relational Mapper) for Node. It is a tool or a level of abstraction which maps/converts data in a relational database into programmatic objects.

SequelizeCLI is the Sequelize Command Line Interface (CLI) that brings thee power Sequelize generators to the your terminal.

Mocha is a test framework running on Node. Used in both unit tests as well as in request specs (features).

Chai is a BDD / TDD assertion library for Node.

FactoryGirl provides factory methods to create test fixtures for automated software testing. Used in both unit tests as well as in request specs (features).

FakerJS helps you real looking data to your tests or database seeders, and it also can be pretty entertaining.

License

MIT

Notes

Once you've generated your application, cd'ed (is that a verb?) into the project folder and installed the dependencies, you need to run a few commands to get the database started.

NOTE: You need to install SequelizeCLI separately or use it with npx for the commands below.

$ npm install -g sequelize-cli
$ sequelize --help
// or
$ npx sequelize --help

Create the database

$ sequelize db:create && NODE_ENV=test sequelize db:create && sequelize db:migrate && NODE_ENV=test sequelize db:migrate

You should get an output similar to this:

Sequelize CLI [Node: 14.8.0, CLI: 6.2.0, ORM: 6.6.2]

Loaded configuration file "database/config/config.json".
Using environment "development".
Database test_api_development created.

Sequelize CLI [Node: 14.8.0, CLI: 6.2.0, ORM: 6.6.2]

Loaded configuration file "database/config/config.json".
Using environment "test".
Database test_api_test created.

Sequelize CLI [Node: 14.8.0, CLI: 6.2.0, ORM: 6.6.2]

Loaded configuration file "database/config/config.json".
Using environment "development".
No migrations were executed, database schema was already up to date.

Sequelize CLI [Node: 14.8.0, CLI: 6.2.0, ORM: 6.6.2]

Loaded configuration file "database/config/config.json".
Using environment "test".
No migrations were executed, database schema was already up to date.

Run tests

We've created one request spec, and one model spec for you as reference. Execute them by running:

$ yarn test

Run tests in VSCode

You can configure your VSCode to run your tests. That will allow you to set breakpoints and use the debugger command and halt the execution of your code.

Go through the process of creating the launch.json file in VSCode and add the following configuration:

"configurations": [
    {
      "name": "Launch Program",
      "program": "${workspaceFolder}/bin/www",
      "request": "launch",
      "skipFiles": [
        "<node_internals>/**"
      ],
      "type": "pwa-node"
    },
    {
      "type": "pwa-node",
      "request": "launch",
      "name": "Mocha tests",
      "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
      "args": [
        "--recursive",
        "--timeout",
        "999999",
        "--colors",
        "--exit",
        "specs"
      ],
      "env": {
        "NODE_ENV": "test",
        "NODE_NO_WARNINGS": "1" // let's stick our head in the sand and silence all warnings
      },
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen"
    }
  ]

Defining Factories

Visit the FactoryGirl documentation for more details. Here, we will show you how to create a basic factory that you can use to test your model and to create fake instances for use in tests. Lets say you have a basic User model:

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  };
  User.init({
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};

Then, in your specs/factories folder, create a users.js with the following code:

module.exports = (factory, Models) => {
  factory.define('User', Models.User, {
    firstName: 'Random',
    lastName: 'Guy',
    createdAt: new Date(),
    updatedAt: new Date()
  })
}

You can use your factory to create one or many instances of the User model:

let author = await factory.create('User')
await factory.createMany('Book', 2, [
      { firstName: "Custom", lastName: "Name" },
      { firstName: "Another", lastName:"Name" }
    ])

There are many other use cases for factories. Make sure to check the documentation.

node_api_generator's People

Contributors

adopi avatar chirag04 avatar christophertrev avatar cilindrox avatar danielfttorres avatar danielrohers avatar defunctzombie avatar dougwilson avatar fishrock123 avatar freewil avatar friederbluemle avatar gmelika avatar haruair avatar jonathanong avatar jpetto avatar justindeguzman avatar mathi123 avatar mde avatar mscdex avatar outsideris avatar palanik avatar pietgeursen avatar platta avatar rgbkrk avatar rramachand21 avatar sheepsteak avatar simonjosefsson avatar tochman avatar zoramite avatar

Watchers

 avatar

Forkers

lucasknudsen

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.