Skip to content

Add new record to a list using sailsjs built-in query language

Notifications You must be signed in to change notification settings

nshimiye/sails-record-list

Repository files navigation

sails-record-list

Add new record to a list using sailsjs built-in query language

Scenario

User wants to receive one joke everyday.

End goal

Create a log of jokes owned by a specific user

foundUser.dailyJokes.add(jokeData);

Step by step

  • create a sails app
sails new sails-record-list
  • create a user api
sails generate api user
rm -rf api/models/User.js
sails generate model user name:string username:string meta:json
  • generate a dailyJoke api
sails generate api dailyJoke
rm -rf api/models/DailyJoke.js
sails generate model dailyJoke content:string author:string source:string meta:json
  • Create one-to-many relationship between user and dailyJoke
// api/models/User.js
    dailyJokes: {
      collection: 'dailyJoke',
      via: 'user'
    }
// api/models/DailyJoke.js
    user: {
      model: 'user'
    }
  • Add logic to fetch one joke for a given user
// api/Controllers/DailyJokeController.js
  • Add logic to save a joke in db
// [api/Controllers/UserController.js]()

...
return DatabaseAccessService.userSaveJoke(userId, { content, author, source });
...

link to complete function

// api/services/DatabaseAccessPrivateUser.js

...
User.findOne({ id }).populate('dailyJokes')
...
foundUser.dailyJokes.add(jokeData);
return this.updateUser(foundUser)
...

link to complete function | link updateUser function

// api/services/DailyJokeService.js

...
getRandom() {
  // @TODO ping your favorite joke source!
  return Promise.resolve({ content, author, source });
}
...
// i use this npm package (one-liner-joke) as a joke source
// so if you copy my code, you will have to add it "npm install one-liner-joke --save"

link to complete function

  • Extra - create a utility service to help with database querying.

  • update a new route to service the dailyJoke request

// config/routes.js
  'GET /user/:id/dailyJoke': {
    controller: 'UserController',
    action: 'dailyJoke'
  }
  • create a dummy user
# GET request
curl http://localhost:1337/user/create?name=mars&username=mars@fusemachines.com
  • request a joke
curl http://localhost:1337/user/1/dailyJoke

Now the joke data will be added to the user's joke list!

About

Add new record to a list using sailsjs built-in query language

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published