skip to Main Content

I am working with node.js and express framework for my rest api server.

I have created get routes with query params and working with them.

But I want to make a functionality like facebook graph api where I can send fields with my api routes such as

/me?fields=address,birthday,email,domains.limit(10){id,name,url}

I am thinking of getting the fields from the query parameters and then splitting them based on , such as

const fields = req.query.fields;
let fieldsArray = fields.split(',');

But how can I pass the sub object attributes and retrieve them from the route like domain field from the above example.

/me?fields=address,birthday,email,domains.limit(10){id,name,url}

2

Answers


  1. Try sending out the request like:

    /me?fields=address,birthday,email,domains.limit%2810%29%7Bid%2Cname%2Curl%7D
    

    There is code for every special character you can get it by doing:

    escape("domains.limit(10){id,name,url}") // Returns domains.limit%2810%29%7Bid%2Cname%2Curl%7D
    

    More details: JavaScript escape() Function

    Hope this solves your issue.

    Login or Signup to reply.
  2. If you use a dot-notation like so

    /me?fields=address,domains.id,domains.name&dbQueryFilters=domains.limit=10
    

    It could mean:

    • I want these fields in my response:
      • address
      • domains:
        • id
        • name
    • Use these to query the db:
      • domains:
        • limit :10

    You can add/remove such query variables until it explicitly conveys what your API does while still being very basic. It’s always in your best interest to keep things simple and basic.

    On the nodeJS side, you can use a library like flat to unflatten the query object:

    var fields = flat.unflatten(req.query.fields)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search