我有一个
JSON文件夹,我想用它来创建一个简单的API.
这是我的文件夹结构的简化版本:
/clients.json
/clients/1/client.json
/clients/2/client.json
…
我的/clients.json文件如下所示:
[
{
"id": 1,"name": "Jon Parker"
},{
"id": 2,"name": "Gareth Edwards"
},...
]
和我的/clients/1/client.json文件看起来像这样:
[
{
"date": "2014-09-12","score": 40,...
},{
"date": "2015-02-27","score": 75,{
"date": "2015-05-10",{
"date": "2016-08-27","score": 60,...
}
]
来自clients.json的id与关联详细信息所在的文件夹相关.
我在客户端文件夹中有很多JSON文件,而不是在客户端单独加载这些文件,我想使用Node.js创建一个API,这给了我更大的灵活性,即……
返回客户名称和id的列表
/客户
返回客户详细信息
/客户/:ID /细节
最重要的是,返回所有客户的名称和相关细节
/客户/所有/细节
我确实开始玩json-server,但它要求你的JSON是一个对象而不是一个数组,不幸的是我坚持使用这个JSON的格式.
感谢任何帮助!
解决方法
使用内置文件系统模块从文件系统中获取文件.
Refer here
这是一个例子.
var fs = require('fs');
exports.getClientDetail = function (id) {
var result;
fs.readFile('/clients/' + id + '/client.json',function (err,data) {
if (err) throw err;
result.push(JSON.parse(data));
});
}
exports.getAllClientsDetail = function () {
// if the id is sequential,you can check if '/clients/' + id + '/client.json' exists for every i from 1 and up. If it does - push it to an array of objects. if for a certain i it does not exist,quit the scan and return the array of objects.
}