Giter VIP home page Giter VIP logo

generator-sails-rest-api's Introduction

generator-sails-rest-api

This project is no longer supported. The only author and contributor who was using Sails and wrote the tool to simplify his regular work quit working with Node.js REST APIs and Sails. Though, if you are interested in take an ownership and became a full-plegded contributor, send a note to [email protected].

Join the chat at https://gitter.im/ghaiklor/generator-sails-rest-api

Downloads Downloads npm version License

semantic-release Commitizen friendly dependencies dev dependencies

Onix-Systems

Yeoman generator that provides already configured and optimized Sails REST API with bundle of predefined features.

Build Status

Version Build Status Coverage Status
Edge (dev) Edge Version Edge Version
Stable (master) Stable Version Stable Version

Features

  • Generator is split in more smaller parts, so that you are able to scaffold models, policies, controllers, etc... separately;
  • Disabled hooks by default: csrf, grunt, i18n, pubsub, session, sockets, views;
  • Flexible questions that allow to you quickly configure database connections, services that you want to use, etc...
  • Implemented authentication layer based on passport with JWT and Local strategies, Facebook, Twitter, VKontakte, GitHub, Instagram, Google Plus and other social networks;
  • Overrides defaults blueprints which simplify CRUD operation in REST API and adds new features like fields or populate in requests;
  • All configuration files cleaned up and optimized for REST API;
  • Some generators can scaffold predefined functionality;
  • Sub-generator that simplifies creating cron configuration;
  • Logger generator can scaffold logging configuration for bunyan, winston or use default Sails logger;
  • Overridden responses which respond with code (Status Code), message (Status Message) and data (Response Data) fields;
  • Bundle of ready-2-use services like CipherService, PusherService (Push Notifications), SmsService and so on... You can check the table with detailed list of implemented services below;
  • Bunch of Sails adapters is already declared in connections.js configuration file so you can easily swap between them;
  • Implemented useful express middleware like Connection: keep-alive and GZip compression. In a nutshell, all what optimizes HTTP performance;
  • Swagger generator can scaffold Swagger UI Explorer for you project;

Getting Started

Console

Install yeoman and generator-sails-rest-api:

npm install -g yo generator-sails-rest-api

Create project directory and initiate the generator under the project directory:

mkdir my-project
cd my-project
yo sails-rest-api

You will be prompted to answer to questions. Answer to those questions and you will get configured Sails project.

After scaffolding the project you can use this project as before. Just run the app.js file or use npm scripts.

npm start

WebStorm 11

Start creating new project and choose Yeoman type:

WebStorm 11 Create New Project

If you have installed sails-rest-api generator then just chose it and click Next. Otherwise, click Install generator and search for sails.

WebStorm 11 Search and Install generator

When you click Next button after the generator was chosen, answer the questions that you'd been prompted.

WebStorm 11 Prompt and Answers

Congratulations, you just have setup your first Sails REST API 👍

Bundled Sails services

Service Name Implemented providers
CipherService JWT
HashService bcrypt
ImageService GraphicsMagick, ImageMagick
LocationService Google, Yandex, FreeGeoIP and a lot of others
MailerService direct, sendmail, SMTP, SES and a lot more
PaymentService BrainTreePayments, Stripe
PusherService Apple Push Notifications, Google Cloud Messaging
SmsService Twilio
SocialService Facebook
StorageService Amazon S3, Local

License

The MIT License (MIT)

Copyright (c) 2015 Eugene Obrezkov aka ghaiklor

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

generator-sails-rest-api's People

Contributors

braunreuthera avatar canabina avatar ghaiklor avatar gitter-badger avatar greenkeeper[bot] avatar greenkeeperio-bot avatar incocode avatar mikedevita avatar sercanov avatar snyk-bot avatar sylwit avatar troggy 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

generator-sails-rest-api's Issues

Creating a user via signup throws a not null constraint error with postgresql

The signup method defined in the AuthController creates the user with this function: User.create(req.allParams()).

console.log(req.allParams()) reveals that the id is undefined.

Postgresql throws up the following error as a result:
Error (E_UNKNOWN) :: Encountered an unexpected error
error: null value in column "id" violates not-null constraint

No route to match the PATCH action verb

PUT /model/:id results in

{
  "code": "OK",
  "message": "Operation is successfully executed",
  "data": {
    ...
  }
}

PATCH /model/:id results in

{
  "code": "E_NOT_FOUND",
  "message": "The requested resource could not be found but may be available again in the future",
  "data": {}
}

Implement returning total count and range in headers

Great feature if API can send X-Total-Count in headers to represent how many records in database exists. Also send X-Range to display pointers in current response. For instance, X-Total-Count: 20 and X-Range: 5-10.

User signup

Hi,
I had a test that ran "Ok" against 0.4.0 tag to /signup a user.
In this it passed a username and password in the body.
Post the 0.5.1 code drop this test is fails.
When I check the user DB after the signup "Created" the username and password are not present as fields so when I try to later /signin this fails with "Missing credentials".
Is this a feature (and if so how to I now signin) or perhaps a bug?
Cheers.

Generate package.json based on answers

Right now I have issue with unused dependencies in package.json. Need to find out the way to generate package.json only with dependencies that we really need.

Improve responses with underscore attributes

When we are working with models declarations, we must follow JavaScript style guides. So any attribute will be named in camelCase. But when we send response, we must send in under_score style.

So my proposal it's replace camelCase attributes with under_score in responses.

Posting to auth/facebook returns E_NOT_FOUND error (404)

I am making a $http request to v1/auth/facebook route
Have defined the baseUrl, appToken as variables in the same file (not in the code over here). Successfully implemented signup and signin using similiar methods. My understanding from reading the wiki is that I need to pass the access_token obtained from facebook as params, and so the code below.

 var fbReq = function(aToken) {                                                                                                                         
           return {                                                                                                                                         
             url: baseUrl + '/facebook',                                                                                                                    
             headers: {                                                                                                                                     
               'application-token': appToken                                                     
             },                                                                                                                                             
             method: 'POST',                                                                                                                                
             params: {'access_token': aToken},                                                                                                              
           };                                                                                                                                               
         },      

Then calling the req through a service method

service.authFb = function(bToken) {                                                                                                                    
      console.log(fbReq(bToken));                                                                                                                          
       $http(fbReq(bToken))                                                                                                                                 
         .then(function(response) {                                                                                                                         
           q.resolve(response);                                                                                                                             
         }, function(error){                                                                                                                                
           console.log(error);                                                                                                                              
           q.reject("There was a problem logging into api server");                                                                                     
         });                                                                                                                                                
         return q.promise;                                                                                                                                  
     };
return service; 

Or do I need to pass in the auth_token as a header??

Override default blueprints

Need to override default blueprints, so each REST route can return more detailed description in header like X-Total or X-Range, etc...

Implement pluralized form only for REST models

Right now when you enable pluralize in config/blueprints.js it will assign pluralized form to controllers like AuthController. That's no good, so need to fix it, maybe with overriding config in controller.

Error: In model (user), invalid connection :: disk

Getting this error on lift:

Thu, 30 Apr 2015 06:07:37 GMT: verbose: sockets hook loaded successfully.
error: In model (user), invalid connection :: disk
error: Must contain an `adapter` key referencing the adapter to use.

This is caused by the fact that /config/etc/development.js sets the default connection to "disk", but that connection is not defined anywhere.

Let me know how you want that fixed and I can send in a PR.

Do we need overriding HTTP method?

Some HTTP clients can only work with simple GET and POST requests. To increase accessibility to these limited clients, the API needs a way to override the HTTP method. Although there aren't any hard standards here, the popular convention is to accept a request header X-HTTP-Method-Override with a string value containing one of PUT, PATCH or DELETE.

Failure after initial install of npm packages

When I attempt to generate a new project...I'm taken through the steps to create the project/DB etc... All of the files get created, some packages get installed...then error is thrown. Any ideas?

I tried with both Postgres and Mongo. I'm using 0.9

C:\Users\eric_swann\AppData\Roaming\npm\node_modules\generator-sails-rest-api\node_modules\dependency-check\index.js:101
      Object.keys(deps).forEach(function (dep) {
             ^
TypeError: Object.keys called on non-object
    at Function.keys (native)
    at C:\Users\eric_swann\AppData\Roaming\npm\node_modules\generator-sails-rest-api\node_modules\dependency-check\index.js:101:14
    at Array.forEach (native)
    at C:\Users\eric_swann\AppData\Roaming\npm\node_modules\generator-sails-rest-api\node_modules\dependency-check\index.js:100:13
    at C:\Users\eric_swann\AppData\Roaming\npm\node_modules\generator-sails-rest-api\node_modules\dependency-check\node_modules\async\lib\async.js:254:17
    at done (C:\Users\eric_swann\AppData\Roaming\npm\node_modules\generator-sails-rest-api\node_modules\dependency-check\node_modules\async\lib\async.js:135:19)
    at C:\Users\eric_swann\AppData\Roaming\npm\node_modules\generator-sails-rest-api\node_modules\dependency-check\node_modules\async\lib\async.js:32:16
    at C:\Users\eric_swann\AppData\Roaming\npm\node_modules\generator-sails-rest-api\node_modules\dependency-check\node_modules\async\lib\async.js:251:21
    at getDeps (C:\Users\eric_swann\AppData\Roaming\npm\node_modules\generator-sails-rest-api\node_modules\dependency-check\index.js:110:14)
    at C:\Users\eric_swann\AppData\Roaming\npm\node_modules\generator-sails-rest-api\node_modules\dependency-check\index.js:95:5

Move from experimental to unstable stability level

I should check all the code located under generator and template and check if everything is ok.

If yes, then I can move to Unstable stability level and continue working only with services.

[x] api folder
[x] config folder
[x] doc folder
[x] test folder

Running node app.js fails with error: missing sails-disk adaptor

Unable to run the server. Installing the sails-disk package with npm still leads to the following error stack

error: Trying to use unknown adapter, "sails-disk", in model `user`.
error: Are you sure that adapter is installed in this Sails app?
error: If you wrote a custom adapter with identity="sails-disk", it should be in this app's adapters directory.
error: Otherwise, if you're trying to use an adapter named `sails-disk`, please run `npm install [email protected]`

node 0.12.1

Implement search on top of find blueprint

When you make request to some collection, you should also can send q parameter where set which text you should find in records. For example, GET /tickets?q=search_text&state=open.

Implement all tests

I add boilerplate for tests here #11 and now need just fill them with test cases. Big task, so need make it in another branch and then merge it.

Twilio module

After generating the project twilio module not installed.

passport service 'localStrategy'

else if (CipherService.create('bcrypt', {content: user.password}).compareHashSync(password))

NEED:

else if (!CipherService.create('bcrypt', {content: user.password}).compareHashSync(password))

Error: Cannot find module 'passport-twitter-token'

Hi. I like what you have done here.
After npm install;sails lift I got the above error. The generated package.json seemed to be missing passport-twitter-token package.
I executed a npm install passport-twitter-token and all good.
Keep up the good work.
Cheers.

Feel free to choose which services you want include

I want to create questions list where developer can check which services he wants to use in application.

And when developer has answered on questions, we are running sub-generators which copies files that he's need.

Sub-generators task - #13

Move steps to CommonJS modules

For example we have initializing section. We can move it to CommonJS module, so index.js will be more easy to read and maintain.

Implement aliases for common queries

To make the API experience more pleasant for the average consumer, consider packaging up sets of conditions into easily accessible RESTful paths. For example, the recently closed tickets query above could be packaged up as GET /tickets/recently_closed.

password lifecycle beforeUpdate

beforeUpdate User model need to check new pass then only to hash pass again;
like this :
beforeUpdate: function(values, next) {
if (typeof values.newPassword != 'undefined' && values.newPassword !== '')

becouse we have problem with forgot pass:
user.password = CipherService.create('bcrypt', {content: newPassword}).hashSync();

Facebook userId is not found

api/services/social/Facebook.js:10
    if (!(options || options.userId || options.accessToken)) {
                            ^
TypeError: Cannot read property 'userId' of undefined
    at new Facebook (api/services/social/Facebook.js:10:29)
    at Object.<anonymous> (api/services/SocialService.js:3:18)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at node_modules/sails/node_modules/include-all/index.js:129:29
    at Array.forEach (native)

Patching

@ghaiklor I was looking over the code and thinking about patching. What if we did something like, for example, taking the services and breaking them into discrete, published modules like sails-service-cipher, sails-service-mailer, and so on.

CipherService.js would then become, simply:

module.exports = require('sails-service-cipher');

That would make it trivial to add new ciphers, mailers, payment gateways, etc and so on in the future without the generator code being affected. It would also make isolating tests much easier.

If you like that idea, we might be able to talk to Sails about auto-registering services like they do for hooks, or, we could create a custom user hook to do just that anyway.

What do you think?

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.