Consume a Github api in javascript using sailsjs

24 Noviembre 2018 »
sailsjs

This is a solution for a little test that I do.

Install a sailsjs api

npm install -g sails

Create a new project. Choose an Empty Sails app

sails new 

Create a simple action2

sails generate action getApi

Edit config/routes.js add new route below of api endpoints.

'GET /getApi' : {action: 'get-api'}

To verify it’s all is ok.. start application,

sails lift

Open the web browser and on url bar type localhost:1337/getApi. Then you will see an ok.

Install node-fetch to use fetch and get the result of Github api.

npm install --save node-fetch

Edit api/controllers/get-api

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const fetch = require('node-fetch');

module.exports = {
  friendlyName: 'Get api',

  description: '',

  inputs: {},

  exits: {},

  fn: async function(inputs, exits) {
    fetch('https://api.github.com/users/luisreinoso/repos')
      .then(apiRes => apiRes.json()) // parse Response to json
      .then(repos => {
        let nameRepos = [];
        repos.forEach(repo => nameRepos.push(repo.name));
        sails.log.info(nameRepos);
        return exits.success({ nameRepos: nameRepos });
      })
      .catch(error => {
        sails.log.error(error);
        return exits.serverError();
      });
  }
};

To verify it’s all is ok.. re-start application,

sails lift

Open the web browser and on url bar type localhost:1337/getApi. Then you will see my repos name.

Notes

  • fetch is not in node by default
  • sails has simple controllers and actions2 to write the api logic

References

  • https://www.npmjs.com/package/node-fetch