Skip to content
Advertisement

map array of object Restfull API with Hapi

I just learned to use the Hapi nodejs Web Framework. I tried a test to post data in Postman and it worked

{
    "status": "success",
    "data": {
        "books": [
            {
                "id": "3aZRShPf",
                "name": "book A",
                "year": 2010,
                "author": "John Doe",
                "summary": "Lorem ipsum dolor sit amet",
                "publisher": "123",
                "pageCount": 100,
                "readPage": 20,
                "finished": false,
                "reading": false,
                "insertedAt": "2021-04-08T09:54:56.022Z",
                "updatedAt": "2021-04-08T09:54:56.022Z"
            }
        ]
    }
}

I wanted to display data like this but I failed and it returned an error

{
    "status": "success",
    "data": {
        "books": [
            {
                "id": "3aZRShPf",
                "name": "Book A",
                "publisher": "123"
            }
        ]
    }
}

and this is so far i got, which part should I fix?

const { nanoid } = require('nanoid');
const books = require('./books');

const getAllBooks = () => ({
  status: 'success',
  data: {
    let book = books.map(book => ({id: book.id, name: book.name, publisher: book.publisher}));
    return book
  },
});

I’m having trouble solving it, hope you can help

Advertisement

Answer

You are not affecting a value to books and have a return statement in your object

Solution:

const { nanoid } = require('nanoid');
const books = require('./books');
    
const getAllBooks = () => ({
  status: 'success',
  data: {
    books: books.map(book => ({id: book.id, name: book.name, publisher: book.publisher}))
      },
});
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement