使用 Hapi 映射对象 Restfull API 的数组

map array of object Restfull API with Hapi

我刚学会使用 Hapi nodejs Web 框架。我尝试在 Postman 中对 post 数据进行测试,结果有效

{
    "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"
            }
        ]
    }
}

我想像这样显示数据,但我失败了,它返回了一个错误

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

到目前为止我已经知道了,我应该修复哪一部分?

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
  },
});

我遇到了麻烦,希望你能帮忙

您正在 data 对象中返回 books。我用过 Object destructuring

data: {
    books: books.map(({ id, name, publisher }) => ({ id, name, publisher })),
  },

const obj = {
  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",
      },
    ],
  },
};

const 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",
  },
];

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

const result = getAllBooks();
console.log( result );

您没有影响书籍的价值,并且在您的对象中有一个 return 语句

解决方案:

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}))
      },
});