What is the method for extracting children from a singular object in json-server rather than an array?

I am currently utilizing json-server as a mock-backend to fetch child data from a single object.
The main table is called sentinel and the secondary table is named sensor

https://i.sstatic.net/1BrRq.png

https://i.sstatic.net/3lOVD.png

It can be observed that sensors is an array, while sentinel is an object.
I have tried using

http://localhost:3000/sentinel?_embed=sensors
, but the response does not align with my expectations. I desire the format to be like this: sensors: [{id: 1}, {id: 2}, etc] https://i.sstatic.net/dVQRZ.png

The official documentation outlines two methods for fetching data from multiple tables:
_embed (include children) and _expand (include parent).

What steps should I take to achieve the desired outcome?

Answer №1

Considering that the sentinel is a singular object in your db.json file, and there can only be one instance of it, it raises questions about the necessity of your query compared to simply retrieving all sensors with sentinelId=10:

/sensors?sentinelId=10

If you attempt this API call:

/sentinel/10/sensors

You will find that it works seamlessly because json-server automatically rewrites the URL to match the previous query.

In case you prefer not to directly utilize the sentinel id within the query, another approach involves using json-server as a module to create a custom route that implements the necessary logic. Here's a simplified illustration that exposes a /sentinel/sensors API to fetch both sentinel data and sensors linked to the current sentinel id:

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const db = router.db;

server.use(jsonServer.bodyParser);
server.get('/sentinel/sensors', (req, res) => {
  const sentinel = db.get('sentinel').value();
  const sensors = db
    .get('sensors')
    .filter({ sentinelId: sentinel.id })
    .value();
  res.send({ ...sentinel, sensors: sensors });
});
server.use(router);
server.listen(3001, () => {
  console.log('Mock server is running on port ' + 3001);
});

This would result in a response similar to the following:

{
  "id": 10,
  "name": "Sentinel",
  "sensors": [
    {
      "id": 1,
      "sentinelId": 10
    },
    {
      "id": 2,
      "sentinelId": 10
    }
  ]
}

For a live demo, check out this StackBlitz link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to retrieve the signature for every method within a class?

Let's consider a scenario where we have a class defined as follows: class Actions { static FooAction = 'foo' as const; someAction1() { return { type: Actions.FooAction, payload: {a: 1, b:2} }} static BarAction = &apos ...

Typescript can represent both optional and required generic union types

Purpose My goal is to establish an optional parameter unless a specific type is provided, in which case the parameter becomes mandatory. Desired Outcome I aim for the get method below to default to having an optional parameter. However, if a type TT is p ...

What are the steps to resolve the error message: "TypeError: argument of type 'NoneType' is not iterable"?

If the request.json contains "id" and "pw" and "pin": This is the line causing issues. ...

Discover the sophisticated approach to iterating through and storing JSON data in Rails

When a click action triggers an ajax request, the JSON data structure is as follows: {"data"=>{"0"=>{"seasons"=>{ "0"=>{"from"=>"2017-01-04", "to"=>"2017-01-07", "weekday"=>"1", "per_day"=>"100", "weekly"=>"230", "weekend"=>" ...

What prevents me from employing my nestjs unique decorator within a constructor?

I am looking to develop a personalized decorator that fetches tenant information. This is the current code snippet I have: export type TenantInfo = { token: string id: string } export const TenantInfo = createParamDecorator( (data: unknown, cont ...

Why is it necessary to use quotations and plus symbols when retrieving values of objects from JSON?

Initially, when attempting to call the PunkAPI for the first time, I was trying to include images (urls are an object returned in the JSON) by append("<img src='beer[i].image_url'/>"); Unfortunately, this did not work because (according t ...

Typescript declaration specifies the return type of function properties

I am currently working on fixing the Typescript declaration for youtube-dl-exec. This library has a default export that is a function with properties. Essentially, the default export returns a promise, but alternatively, you can use the exec() method which ...

Troubleshooting JSON compatibility problem in Django with Internet Explorer

Struggling with JSON compatibility issues in Internet Explorer (IE9). I've scoured the internet and tried various solutions to no avail. Decided it was time to create a Stack Overflow account and pose my first question. My JSON and jQuery/AJAX-based ...

Design an element that stretches across two navigation bars

Currently, I have implemented two Navbars on my website as shown in the image below: https://i.stack.imgur.com/4QmyW.png I am now looking to include a banner that clearly indicates that this site is a test site. In addition, I would like to incorporate a ...

Issue with Image Uploads (NodeJs/Formidable)

I tried using [email protected] to upload a form that includes an image, following a tutorial. However, I encountered the following error. How can I troubleshoot this issue? Error: The "path" argument must be of type string or an instance ...

Issue with NgFor nested component not refreshing after @Input modification

When populating a component called ContactUpdatableItem within a NgFor, the code looks like this: <section class="plContactCreation-listItem" *ngFor="let contact of contacts$ | async; index as idx" > <contact-updatable-item [c ...

The parameters used in the json.parse function in javascript may be difficult to interpret

Currently, I am examining a JavaScript file on this website. It contains the following code: let source = fs.readFileSync("contracts.json"); let contracts = JSON.parse(source)["contracts"]; I'm curious about what exactly the JSON.parse function is d ...

An effective method to utilize .map and .reduce for object manipulation resulting in a newly modified map

Here's an example of what the object looks like: informations = { addresses: { 0: {phone: 0}, 1: {phone: 1}, 2: {phone: 2}, 3: {phone: 3}, 4: {phone: 4}, 5: {phone: 5}, }, names: { 0 ...

From Spring MVC to JSON data output

I have a JAVA EE backend and I am using Spring MVC. Currently, I have an AJAX call set up as follows: function getAllProjects() { $.getJSON("project/getall", function(allProjects) { ??? }); } In my backend system: @Reques ...

Adding an additional element to an object - crossroads of combining types versus sequential examination

Here's a query for you: AppendToObject. When I first tackled this question, my initial instinct was to utilize type intersection like so: type AppendToObject<T, U extends PropertyKey, V> = T & {[P in U]: V} Unfortunately, this solution did ...

Display or conceal an icon based on the data in the field

Can someone provide guidance on how to make an icon appear or disappear based on the logic within [ngIf]? The icon should only be displayed if there is information in a specific field. Should I implement this inside ngIF or in my TS file? Can the icon cl ...

Swapping out 'useResult' in graphql for Vue and Apollo: A step-by-step guide

I need to replace the useResult function that is fetching data from GraphQL with a computed function. const locationOptions = useResult( result, [], ({ getLocations }): Option[] => formatOptions(getLocations) ) Instead, I want ...

“Rails encountering issues with proper parsing of QPX Express API object”

I've been struggling for a while now to understand why my JSON object isn't working properly when passed through AJAX to Rails using Typhoeus. I apologize if this seems like a beginner question, as I'm fairly new to web development. Despite ...

Getting values from a JSON array in Swift 4 - a step-by-step guide

I have the following code snippet written in Swift 4 using Alamofire: Alamofire.request("http://xxxx.pl/id=1", method: .get, parameters: nil) .responseJSON { response in let jsonResponse = JSON(response.result.value!) let resData = jsonRespon ...

Transforming Typescript types into object literals

type SelectData = { name?: boolean; address?: boolean; } const selectData: SelectData = { name: true } const untypedSelectData = { name: true } I am looking to enforce TypeScript to throw an error if there is an attempt to assign a property that ...