Ben
Ben

Reputation: 109

How to use dynamic query for the rest api

I am beginner of javascript and I am trying to create a simple rest api using node.js. This is so far, I have it. I have a database called testDb and table called testMeasurement in influxdb. testMeasurement table contains DateOfBirth,ID,FirstName,LastName

(ID is tag in my testMeasurement table)

var express = require('express');
const Influx = require('influx')

var app = express();

const influx = new Influx.InfluxDB('http://user:password@localhost:8086/testDb')

app.listen(3000, 'localhost');

    app.get('/myapi', function (req, res) {
        influx.query('select * from testMeasurement').then(result => {
          res.json(result)
        }).catch(err => {
          res.status(500).send(err.stack)
        })
      })

Now, Above gives me all the data which I have in testMeasurement table from database "testDb".

How do I define my query in a dynamic way so that I can filter my result? for eg. if I type localhost/myapi/ID={someValue}, this should give me the relatedData of that ID.

Any advice would be so helpful.

Upvotes: 0

Views: 2051

Answers (1)

Michael Sandoval
Michael Sandoval

Reputation: 146

There are many ways to achieve what you want. The best way to do it is using wildcards. Example:

app.get('/myapi/:userId', (req, res) => {
    var query_str = 'select * from testMeasurement';

    if (req.params.userId){
        query_str += ' where id = ' + req.params.userId;
    } 

    influx.query(query_str).then(result => {
        res.json(result)
    }).catch(err => {
        res.status(500).send(err.stack)
    })
});

That implies that you must have a structured API to consume, having nodes for each item. If you just want to test a little bit, one basic example is to test for GET params like:

app.get('/myapi', function (req, res) {
    var query_str = 'select * from testMeasurement';

    if (req.query.id != null){
        query_str += ' where id = ' + req.query.id;
    } 

    influx.query(query_str).then(result => {
        res.json(result)
    }).catch(err => {
        res.status(500).send(err.stack)
    })
})

Hope it helps!

Upvotes: 2

Related Questions