0

I am having an issue where I can't destructure from event.body.

exports.handler = async (event, context) => {
    const { items } = event.body;
    const allItems = await getProducts();

    return {
        statusCode: 200,
        body: 'I have charged your card!',
    };
};

If I look at event.body, I get {"items":[{"id":12,"quantity":4}]} but when I try and get items from event.body, it always comes back as undefined.

So I believe the issue is in my getProducts function.

const getProducts = async () => {
    const categories = [];
    const items = [];
    const r = await fetch(url)
        .then(response => response.json())
        .then(json => FireStoreParser(json))
        .then(json => {
            const documents = json['documents'];
            Object.keys(documents).forEach(function(key) {
                categories.push(documents[key]);

                Object.keys(categories[key]['fields']).forEach(function(key2) {
                    items.push(categories[key]['fields']['items']);
                });
            });
        });

    return items;

I need to access each items id. This is what getProducts returns

[
  [
    {
      price: 220,
      imageUrl: 'https://i.ibb.co/0s3pdnc/adidas-nmd.png',
      name: 'Adidas NMD',
      id: 10
    },
    {
      name: 'Adidas Yeezy',
      price: 280,
      id: 11,
      imageUrl: 'https://i.ibb.co/dJbG1cT/yeezy.png'
    },
    {
      imageUrl: 'https://i.ibb.co/bPmVXyP/black-converse.png',
      price: 110,
      id: 12,
      name: 'Black Converse'
    },
    {
      imageUrl: 'https://i.ibb.co/1RcFPk0/white-nike-high-tops.png',
      id: 13,
      price: 160,
      name: 'Nike White AirForce'
    }
]
]
Chris
  • 51
  • 1
  • 8
  • 1
    is `event.body` a string or an object? – CollinD Aug 07 '21 at 15:02
  • ^^ because `undefined` is what you get if you do `const { items } = "any string";` – T.J. Crowder Aug 07 '21 at 15:07
  • Apparently it is a string. How would I pull the id from it then? – Chris Aug 07 '21 at 15:15
  • 2
    `const { items } = JSON.parse(jsonString);` – Yousaf Aug 07 '21 at 15:17
  • `const { items } = JSON.parse(jsonString);` This works but sometimes it would contain multiple items so how would I iterate over it and get each item `const cartWithProducts = items.map(({ id, quantity }) => { const item = allItems.find(p => p.id === id); });` Item is always undefined. – Chris Aug 07 '21 at 15:24

1 Answers1

0

In my getProducts I need to return items[0] instead of just items.

Then in I just need to do this and I can get the correct item:

const cartWithProducts = items.map(({ id, quantity }) => {
        const item = allItems.find(p => p.id === id);
            console.log(item)
    });
Chris
  • 51
  • 1
  • 8