I have a folder of JSON files that I'd like to use to create a simple API from.
Here's a simplified version of my folder structure:
/clients.json
/clients/1/client.json
/clients/2/client.json
...
my /clients.json
file looks like this:
[
{
"id": 1,
"name": "Jon Parker"
},
{
"id": 2,
"name": "Gareth Edwards"
},
...
]
and my /clients/1/client.json
file looks like this:
[
{
"date": "2014-09-12",
"score": 40,
...
},
{
"date": "2015-02-27",
"score": 75,
...
},
{
"date": "2015-05-10",
"score": 75,
...
},
{
"date": "2016-08-27",
"score": 60,
...
}
]
The id from clients.json
relates to the folder in which the associated details are.
I have a lot of JSON files in the clients folder and rather than loading these all individually on the client side, I wanted to create an API using Node.js that gives me more flexibility, i.e...
returning a list of client names and id's
/clients
returning the client details
/clients/:id/details
and most importantly returning all clients with there names and associated details
/clients/all/details
I did begin playing with json-server, however it requires that your JSON be an object rather than an array, and I'm stuck with the format of this JSON unfortunately.
Appreciate any help!
Use the built-in file system module to get files from the file system.
Refer here
Here's an example.
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.
}
You can require
the json directly as an object in node, something like this:
app.get('/clients/:id/details', (req, resp) => {
const id = req.params.id;
const data = require(`./clients/${id}/client.json`); // or whatever path
resp.send(data)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With