简体   繁体   English

如何对其余API使用动态查询

[英]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. 我是javascript的初学者,正在尝试使用node.js创建一个简单的rest api。 This is so far, I have it. 到目前为止,我已经掌握了。 I have a database called testDb and table called testMeasurement in influxdb. 我有一个名为数据库testDb和表称为testMeasurement在influxdb。 testMeasurement table contains DateOfBirth,ID,FirstName,LastName testMeasurement表包含DateOfBirth,ID,FirstName,LastName

(ID is tag in my testMeasurement table) (ID是我的testMeasurement表中的标记)

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". 现在,上面给了我来自数据库“ testDb”的testMeasurement表中的所有数据。

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. 如果我输入localhost/myapi/ID={someValue} ,这应该给我该ID的relatedData。

Any advice would be so helpful. 任何建议都将非常有帮助。

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. 这意味着您必须要使用结构化的API,并且每个项目都有节点。 If you just want to test a little bit, one basic example is to test for GET params like: 如果您只想测试一点,一个基本的示例是测试GET参数,例如:

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! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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