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

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]

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

Displaying the ngFor data in the HTML section

Struggling with passing an array from poll-vote.component.ts to poll-vote.component.html. The data involves radio buttons and I'm using ngFor loop with index, but it's not working as expected: Here is my poll-vote.component.ts code: import { Com ...

Improving large JSON data with multiple calls

In my Java/Spring web application, I have implemented a feature where each user can manage their own word list. Whenever a user adds or removes a word, an AJAX call is made to send a JSON object with the word information to the server for processing. The s ...

Is JSONP necessary for accessing the API subdomain?

Currently in the process of setting up an application with the API being hosted at http://api.project.com while the main app will reside at https://app.project.com. This app is going to be entirely based on angular.js. I'm curious if JSONP is the onl ...

Exploring the Depths of Multidimensional JSON Arrays in PHP

I am currently working on developing a web-based file manager that allows me to organize, view, create, edit, and delete folders and files. In order to store information about these folders, files, and subfolders, I am in need of an appropriate data struct ...

Using vue-class-component: A guide on creating and setting up reactive data

I am currently working with Vue.js using TypeScript and vue-class-component. My goal is to create a custom component with reactive data. Below is the code I have so far: <template> <div> <input v-model="data.name" placeholder=" ...

Tips for storing an unmatched result in an array with a Regexp

Is it possible to extract the unmatched results from a Regexp and store them in an array (essentially reversing the match)? The following code partially addresses this issue using the replace method: str = 'Lorem ipsum dolor is amet <a id="2" css ...

Unit Testing Sentry with Jest Framework using TypeScript in a Node.js Environment

I'm in the process of integrating Sentry into my existing NodeJS project, but I'm facing an issue with mocking a specific part of the Sentry code. Here's the relevant Sentry code snippet: const app: express.Express = express(); Sentry.init ...

``The importance of properly formatting a text string before encoding it into

Currently in the process of converting an XML document to JSON via a PHP backend and then sending it back to the frontend using AJAX. This is achieved through the following code snippet: print_r(json_encode($result_xml)); If you want to view the response ...

Discover more efficient methods for utilizing generics in hierarchical objects within typescript

How can I optimize the structure of an object that contains nested objects in Typescript to minimize type repetitions? type itemType = { [key: string]: { [key: string]: { [key: string]: { [key: string]: string } }; }; }; ...

What is the proper way to address the error message regarding requestAnimationFrame exceeding the permitted time limit?

My Angular application is quite complex and relies heavily on pure cesium. Upon startup, I am encountering numerous warnings such as: Violation ‘requestAnimationFrame’ handler took 742ms. Violation ‘load’ handler took 80ms. I attempted to resolve ...

Incorporating a new attribute into the JQueryStatic interface

I am trying to enhance the JQueryStatic interface by adding a new property called someString, which I intend to access using $.someString. Within my index.ts file, I have defined the following code: interface JQueryStatic { someString: string; } $.s ...

Managing Prisma error handling in Express

Dealing with error handling using ExpressJS and Prisma has been a challenge for me. Anytime a Prisma Exception occurs, it causes my entire Node application to crash, requiring a restart. Despite looking at the Prisma Docs and doing some research online, I ...

Guide to downloading and parsing JSON using OperationQueue in Swift

I've encountered an issue with a seemingly straightforward problem. The parse operation is being executed before the download operation's completion handler finishes, resulting in no data being available for parsing. You can simply insert the fol ...

Is it feasible to utilize the HTML5 video tag in conjunction with a JSON callback?

Curious about the possibility of a video page layout featuring a main screen and smaller clickable screens below it. When clicking on one of the smaller screens, the main screen would display the selected video, similar to YouTube. We have obtained data f ...

Angular - Enhancing the page with valuable information

Recently, I've been developing an Angular application that is designed to function as a digital magazine. This app will feature articles, news, reviews, and more. Along with this functionality, I am looking to include an admin panel where I can easily ...

What is the best way to manage destroyed objects?

I've been working on a PIXI.js application and I'm faced with the challenge of managing resources to prevent memory leaks. To address this issue, I am utilizing the DisplayObject.destroy method. When a display object is destroyed, many of its in ...

The elements appear tiny while the resolution is excessively large on the Ionic mobile device

I recently finished developing an Ionic project and successfully compiled it for both iOS and Android. Surprisingly, everything seems to be working fine on Android devices but I am encountering issues on iOS and when viewing the project from Chrome's ...

Compilation failure due to Typescript initialization issue

Encountering a TypeScript error in my IntelliJ-Idea 2017.1.1 IDE I have enabled JavaScript, NodeJS, and TypeScript Compiler. I have exhausted all solutions but the issue persists, perhaps I am missing something. Error: Initialization error (typescript ...

Exploring AngularJS: Effortlessly Retrieving Object Values

HTML: <div ng-app = "" ng-controller = "personController"> <p>Persoon: <select ng-model="persoon"> <option ng-repeat="person in persons">{{person.FirstName}} {{person.FamilyName}}</option> & ...

JSON TypeScript compliant interface

My problem is quite common, but the solutions found on stackoverflow are not suitable for my specific case. I have a collection of objects that I need to manipulate, save, and load as json files. Here's an example of the interface: type jsonValue = s ...