Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Simple Node.js API from JSON files

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!

like image 842
DanV Avatar asked Dec 09 '16 00:12

DanV


2 Answers

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.
}
like image 109
guysigner Avatar answered Oct 06 '22 22:10

guysigner


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)
});
like image 20
7zark7 Avatar answered Oct 06 '22 21:10

7zark7