Integration with external api

Send requests

Let's say you must get users from api:
https://jsonplaceholder.typicode.com/users

For send request and get data you can use http.request

const http = require('http')
const req = http.request({
    URL: 'https://jsonplaceholder.typicode.com/users',
    method: 'GET',
    sendTimeout: 1000, receiveTimeout: 30000, connectTimeout: 1000,
    keepAlive: true,
    compressionEnable: true,
    headers: {}
  })
  const resp = req.end()
  const userData = JSON.parse(resp.read('utf-8'))

Next example is more complete, with custom buttons and saving data to db.

Create new meta file req_user.meta

{
  "caption": "Users", // entity name
  "description": "users",  // entity description
  "attributes": [
    {
      "name": "name",
      "dataType": "String",
      "size": 255,
      "caption": "User Name",
      "description": "User Name",
      "allowNull": false
    },
    {
      "name": "email",
      "dataType": "String",
      "size": 255,
      "caption": "User Email",
      "description": "User Email",
      "allowNull": false
    },
    {
      "name": "phone",
      "dataType": "String",
      "size": 255,
      "caption": "User Phone",
      "description": "User Phone",
      "allowNull": false
    },
    {
      "name": "website",
      "dataType": "String",
      "size": 255,
      "caption": "User Website",
      "description": "User Website",
      "allowNull": false
    }
  ],
  "mixins": { // the mandatory section (can be empty)
    "mStorage": {
    }
  }
}

Create req_user.js next to the file req_user.meta

const UB = require('@unitybase/ub')
const http = require('http')
const me = req_user
me.entity.addMethod('addUsers')

me.addUsers = function (ctx) {
  // send requst
  const req = http.request({
    URL: 'https://jsonplaceholder.typicode.com/users',
    // host: host,
    // port: port,
    // path: path,
    method: 'GET',
    sendTimeout: 1000, receiveTimeout: 30000, connectTimeout: 1000,
    keepAlive: true,
    compressionEnable: true,
    headers: {} // {Authorization: 'Basic ' + 'QURNSU46MTIzNDU2'}
  })
  const resp = req.end()
  if (resp.statusCode !== 200) {
    ctx.mParams.result = false
    return
  }

  const userStore = UB.DataStore('req_user')
  // get data from response
  const userData = JSON.parse(resp.read('utf-8'))
  // insert data to db
  userData.forEach(user => {
    userStore.run('insert', {
      execParams:
        {
          name: user.name,
          email: user.email,
          phone: user.phone,
          website: user.website
        }
    })
  })
  ctx.mParams.result = true
}

In this file we create custom method addUsers which sends request to https://jsonplaceholder.typicode.com/users, parses, and stores data from response to database.

Create shortcut (right click on left panel -> Add shortcut) with parameters:

Desktop: City Requests

Shortcut caption: Users

Code: req_user

Source code:

{
  "cmdType": "showList",
  "cmdData": {
    "params": [{
      "entity": "req_user",
      "method": "select",
      "fieldList": [
        "*"
      ]
    }]
  },
  "customActions": [{
    "actionText": "Add users",
    "glyph": 61465,
    "text": "Add users",
    "handler": function(cmp) {
      $App.connection.run({
        entity: 'req_user',
        method: 'addUsers'
      }).then(function(result) {
        if (result) {
          $App.dialogInfo('Завантажено успішно')
        } else {
          $App.dialogInfo('Під час завантаження сталася помилка')
        }
      })
    }
  }]
}

In customActions section we add button with handler which call addUsers method from req_user.js

After this steps you must see button:

addUsers button

After click on this button and reload users must be shown:

saved users

Receiving requests

If you want to receiving requests on some endpoint in your app, you must register this endpoint and set handler for it by the registerEndpoint method.

const App = require('@unitybase/ub').App
App.registerEndpoint('addUser', addUser, false)

First parameter is endpoint literal. In this example request on http://localhost/addUser will be handled.

Next parameter is handler function.

Third parameter is whether required authentication headers.

Get data from query string

In next code in function addUser we parse user fields from query string and insert them to db.

const UB = require('@unitybase/ub')
const App = require('@unitybase/ub').App
const querystring = require('querystring')

App.registerEndpoint('addUser', addUser, false)

function addUser (req, resp) {
  const { name, email, phone, website } = querystring.parse(req.parameters)
  const userStore = UB.DataStore('req_user')
  userStore.run('insert', {
    execParams:
      {
        name,
        email,
        phone,
        website
      }
  })
  resp.statusCode = 200
  resp.writeEnd('user addded')
}

Paste this code to addUserEndpoint.js and add line require('./addUserEndpoint') to req.js.

After server restart you can save users from requests.

request

user added

Get request body data

Use req.read() to get data from body.

Here is function addUser in this case:

function addUser (req, resp) {
  const { name, email, phone, website } = JSON.parse(req.read())
  const userStore = UB.DataStore('req_user')
  userStore.run('insert', {
    execParams:
      {
        name,
        email,
        phone,
        website
      }
  })

  resp.statusCode = 200
  resp.writeEnd('user addded')
}

After sending next request, user will be added.

send post

Next step