简体   繁体   中英

Create a REST API in nodejs

I have a postgresql table, which looks like :

man_id subgroup power group
1 sub_A 1 Group_A
2 Sub_B -1 Group_A
3 Sub_A -1 Group_B
4 Sub_B 1 Group_B
5 Sub_A -1 Group_A
6 Sub_B 1 Group_A
7 Sub_A -1 Group_B
8 Sub_B 1 Group_B

We have a power calculation here, it works like,

Total Power of Subgroup Sub_A in the Group Group_A is (1 + (-1) ) = 0
Total Power of Subgroup Sub_B in the Group Group_A is ((-1) + 1 ) = 0
Total Power of Subgroup Sub_A in the Group Group_B is ((-1) + (-1) ) = -2
Total Power of Subgroup Sub_B in the Group Group_B is (1 + 1 ) = 2

So the power of `Sub_A` in the Group_A is not equal to power of Sub_A in the Group_B
So the power of Sub_B in the Group_A is not equal to power of Sub_B in the Group_B

I want to create a REST API in nodejs where I can query with subgroup name. If for a same subgroup name power is equal across all the other group names, then it will return yes, else No.

As an example,

http://localhost:3000/api/check/Sub_A will return NO

http://localhost:3000/api/check/Sub_B will return NO

I can connect the database and list down all the entries in a JSON. Below is my code,

http://localhost:3000/api/lists will return all the entries in the DB.

query.js

var promise = require('bluebird');

var options = {
  // Initialization Options
  promiseLib: promise
};

var pgp = require('pg-promise')(options);
var connectionString = 'postgres://localhost:5432/lists';
var db = pgp(connectionString);

// add query functions

module.exports = {
  getAllList: getAllList
};


function getAllList(req, res, next) {
  db.any('select * from dataset')
    .then(function (data) {
      res.status(200)
        .json({
          status: 'success',
          data: data,
          message: 'Retrieved ALL Data'
        });
    })
    .catch(function (err) {
      return next(err);
    });
}

index.js

var express = require('express');
var router = express.Router();

var db = require('../queries');


router.get('/api/lists', db.getAllList);



module.exports = router;

You can try using the req.params object from the Express request object

http://localhost:3000/api/check/{Subgroup}

The following code might help you

 app.get('/api/check/:subgroup?', (req, res) => { const subgroup = req.params.subgroup; res.json(...); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM