Giter Site home page Giter Site logo

ndelvalle / generator-api Goto Github PK

View Code? Open in Web Editor NEW
251.0 12.0 50.0 1.44 MB

🚀 Yeoman generator for creating RESTful NodeJS APIs, using ES6, Mongoose and Express

Home Page: https://ndelvalle.github.io/generator-api/

License: MIT License

JavaScript 98.13% Dockerfile 1.87%
yeoman yeoman-generator node rest-api es6 mongoose api expressjs

generator-api's Introduction

generator-api

Codeship Status for ndelvalle/generator-api dependencies Status devDependencies Status Codacy Badge

NPM

Yeoman generator for creating RESTful NodeJS APIs, using ES6, Mongoose and Express. The fastest way to get your project up and running using an awesome stack.

generator

Getting started

  • Make sure you have yeoman installed on your machine: npm install -g yo
  • Install the generator globally: npm install -g generator-api
  • Run: yo api, or yo and choose Api option

Running the generated project

Make sure you have node version >= 6 because this project uses native supported ES6 features.

Development

  • Run: mongod to start the local mongodb in a separated terminal instance (If you don't have mongodb installed locally, visit It's webpage to learn how to install it).
  • Run: npm run dev to run the app (By default the app will run at localhost:8080, you can change this in the config file).

Did you choose Docker (:whale:) support?

You only need Docker and docker-compose installed, forget about having node, mongodb or npm.

  • Run: docker-compose up to run the app. You might need sudo for this one.

NOTE: The Dockerfile uses node:latest as its starting point, if you wish to use another version of Node check out the available ones here.

Production

You'll likely be consuming mongodb as a service, so make sure to set the env var pointing at it. Then run npm start.

Using Docker

Build the Docker container and run it:

sudo docker build -t <image-name> .
sudo docker run \
  -p <host-port>:8080 \
  -d <image-name> \
  -e MONGO_DB_URI=mongodb://<username>:<password>@<host>:<port> \
  npm run start

Architecture

Assuming we use user and pet models the generated project will look like this:

├───index.js
├───routes.js
├───package.json
├───config.js
└───lib/
|   ├───controller.js
|   ├───facade.js
└───model/
    ├───user/
    │   └───controller.js
    |   └───facade.js
    |   └───router.js
    |   └───schema.js
    └───pet/
        └───controller.js
        └───facade.js
        └───router.js
        └───schema.js

Controller:

HTTP layer, in this instance you can manage express request, response and next. In lib/controller are the basic RESTful methods find, findOne, findById, create, update and remove. Because this class is extending from there, you got that solved. You can overwrite extended methods or create custom ones here.

Facade:

This layer works as a simplified interface of mongoose and as business model layer, in this instance you can manage your business logic. Here are some use case examples:

  • Validate collection x before creating collection y
  • Create collection x before creating collection y

In lib/facade you have the basic support for RESTful methods. Because this class is extending from there, you got that solved. You can overwrite extended methods or create custom ones here. Also you can support more mongoose functionality like skip, sort etc.

Model subgenerator

Once you have the generated project, if you want to add a new model you can simply run yo api:model. This will generate a new folder under model, in order to make it work, you just need to import the route into the routes.js.

Example:

  • Run yo api:model, write foo (What ever model name you want)
  • Go to routes.js and import the new generated model route const foo = require('./model/foo/router')
  • Use the imported route router.use('/foo', foo)

Contributing

Contributors are welcome, please fork and send pull requests! If you find a bug or have any ideas on how to improve this project please submit an issue.

License

MIT License

Style guide

Standard - JavaScript Style Guide

generator-api's People

Contributors

codacy-badger avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar gillchristian avatar jobobo21 avatar martincarrera avatar matiastucci avatar ndelvalle avatar tomexa avatar vladimirmilenko avatar xlarry avatar ylcoder 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  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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

generator-api's Issues

Clean Install - First Start Error

Just completed install and giving a try. After completing generation process, I execute npm run dev as documented. I can debug this further this evening, but figured I would let you know of immediate issues

  % npm run dev                                                                                                                                                                                                                       !4941

> [email protected] dev /Users/mikeerickson/Documents/Projects/test
> nodemon index.js

[nodemon] 1.9.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
/Users/mikeerickson/Documents/Projects/test/node_modules/milieu/lib/milieu.js:5
let   ini;              // Lazy loaded
^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    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 Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/Users/mikeerickson/Documents/Projects/test/node_modules/milieu/index.js:2:16)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
[nodemon] app crashed - waiting for file changes before starting...

How to chain middleware in routes.

Hi,

Thanks for creating this amazing project. I'm new to es6 and need some help router file.
I use chain auth middleware in routes like this before.
router.get('/', auth.hasRole('admin'), controller.find)

Using above code results in following error.
Cannot read property 'facade' of undefined

Could please explain how can i chain middleware with new syntax.
router.route('/test').get((...args) => controller.test(...args));

Also if you can explain facade pattern in readme file with example it will really helpfull

Switching to restify instead of expressjs

This is a proposition of switching from https://github.com/expressjs/express to https://github.com/restify/node-restify. Some of the reasons are:

  • Since the idea of a generator is to be used presumably for REST API projects, meaning no server-side page rendering, the app could be far lighter by using restify framework.
  • restify is more robust when it comes to error handling (http://restify.com/#error-handling), since it comes with built-in Error objects that are easily mapped to proper http errors.
  • A lot of parsers are also built-in (http://restify.com/#bundled-plugins).

gulp serve (copy part) is slow

Hi! When I run gulp serve, I see the following on my project :

image

It doesn't have lots of files to move (only two models / routes etc... ) It is slow since the verry first use.

Error at npm run dev

On node v4.4.7 with a generated app using defaults I get:

[nodemon] 1.10.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
/Users/Jeffrey/Projects/test-api/node_modules/milieu/lib/milieu.js:4
let   ini;              // Lazy loaded
^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/Users/Jeffrey/Projects/test-api/node_modules/milieu/index.js:2:16)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)

Updating the eslintignore file doesn't seem to help. Can you help ?

How to use 'lib/controller' handleError and validationError?

Hi,

I can see handleError and validationError functions inside lib/controller but they are not used any where. Could you please explain how to use them generated controllers.? Do you have any suggestion about how to do effiecent global error handling.

  • Sushil

module structure option?

great job !
what about the option of getting the files structured by modules (users, customers, etc )
and not by type of file ( models, controllers, etc)
thanks
Chris

Adding JWT, Swagger and versioning

How do we hook swagger, JWT packages on to the platform and what could be the best model for adopting api versioning within the platform?

Models file naming

This is how model files are named now:

└───model/
    ├───user/
        └───user-controller.js
        └───user-facade.js
        └───user-router.js
        └───user-schema.js

I was just wondering since the directory already is named after the model, I think it would make sense to remove the model name from the files:

└───model/
    ├───user/
        └───controller.js
        └───facade.js
        └───router.js
        └───schema.js

What do you think @ndelvalle ?

Add testing support

I really like the concept behind this starter and I will be happy to contribute at some point. I think one of the few things missing is the possibility to the user to add testing or not.

/resource/:id wrong behaviour

The search results wont be correct as current route defaults for /resource/:id use findOne (with the req.query which is blank for this route)

Instead routes should use findById with the req.params.id to deliver the correct response

// routes.js
router.route('/events/:id')
    .get((...args) => controllers.event.findById(...args));

Duplicate users in mongo

Hi, how do I prevent duplicate users created in the database? for example having an email as their primary source of identity.

I have created multiple users with the same email but the only thing that changes is their _id, I don't want email to be the same. I've tried multiple things including using some of the build in functions but I cant get it to work.

Any help please?

Question: where to place additional code for model, with different route?

Thanks for boilerplate. It's very helpful.
It's my first real project with express and mongoose, and I'm sorry if my question is stupid.
I'm working on dictionary, and have an Article model:

const articleSchema = new Schema({
  wordTable: { type: String, required: true },
  wordForms: { type: [String] }
})

I need new route /search/:text
This route not related to /article route, but method still related to article model:
Article.find({ wordForms: text })
I'm a little confused, where to place this code.
Can you give me an advice please?

Question: Integration with api docs

This is more an enhancement and a question, but it would be nice to have at least optional, support or integration with API docs: http://apidocjs.com, since this is a restful API design, make sense to have some kind of API documentation

Trying to scaffold via Yo leads to exception

? Server name: apiYotest
? Server description: trying yo to see nodejs api with mongo
? Server version: 0.1.0
? Author name: Myk
? Author email:
? Business models: (singular and comma separated) user, pet
? what should the database be named? api-yotest

result:

events.js:141
      throw er; // Unhandled 'error' event
      ^
AssertionError: Trying to copy from a source that does not exist: /usr/local/lib/node_modules/generator-api/generators/app/templates/.gitignore
    at EditionInterface.exports._copySingle (/usr/local/lib/node_modules/generator-api/node_modules/mem-fs-editor/lib/actions/copy.js:45:3)
    at EditionInterface.exports.copy (/usr/local/lib/node_modules/generator-api/node_modules/mem-fs-editor/lib/actions/copy.js:23:17)
    at gitignore (/usr/local/lib/node_modules/generator-api/generators/app/index.js:131:15)
    at Object.<anonymous> (/usr/local/lib/node_modules/generator-api/node_modules/yeoman-generator/lib/base.js:431:23)
    at /usr/local/lib/node_modules/generator-api/node_modules/run-async/index.js:26:25
    at /usr/local/lib/node_modules/generator-api/node_modules/run-async/index.js:25:19
    at /usr/local/lib/node_modules/generator-api/node_modules/yeoman-generator/lib/base.js:432:9
    at processImmediate [as _immediateCallback] (timers.js:383:17)

How to add api functions to controller

Hi, can you please provide me with an example of how to implement a function or route for example getUser, I am struggling to figure out how to implement a function in the controller for example.

EDIT* What I'm basically asking is if you can provide me an example of how I would add a custom function that just returns some text.

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.