Inserting fetch response into a collection

If someone could give some guidance a would really appreciate it. I am able to console log json from a fetch request, but I need to insert the data into a collection.

What I have so far:

BACK END CODE:
// Filename: backend/sendEmail.jsw  (web modules need to have a *.jsw* extension)
import { fetch } from 'wix-fetch';
import wixData from 'wix-data';
// wix-fetch is the API we provide to make https calls in the backend
//const user = "xxxx";
//const pass = "xxxx"
const api_key_id = 'xxxxx';
const api_key_secret = xxxxx';
export function sendOrder(address, zipcode, file) {
                return fetch('https://api.housecanary.com/v2/property/sales_history', {
                  body: JSON.stringify([{ "address": address, "zipcode": zipcode }]),
                  headers: {
    Authorization: "Basic xxxxxx
    'Content-Type': "application/json",
                  },
                  method: 'post',
  })
  .then((res) => res.json())
  .then((data) => console.log(data))
}
FRONT/PAGE CODE:
import { sendOrder } from 'backend/serviceModule';
export function button1_click(event, $w) {
                sendOrder(
  $w("#address").value,
  $w("#zipcode").value)
}
JSON FROM FETCH RESPONSE:
[
{
"property/sales_history":{
"api_code_description": "ok",
"api_code": 0,
"result":[
{
"fips": "12103",
"event_type": "arms_length_sale",
"apn": "24-30-15-02733-000-0240",
"grantee_1": "LEWIS",
"grantee_2": "LEWIS",
"grantor_2": "BREMM",
"record_page": "731",
"grantor_2_forenames": "JANET",
"amount": 265000,
"grantee_1_forenames": "EDDIE L",
"record_date": "2003-09-08",
"grantee_2_forenames": "SUANN E",
"grantor_1": "BREMM",
"record_doc": "03-380217",
"record_book": "13048",
"grantor_1_forenames": "DAVID A"
}
]
},
"address_info":{
"status":{
"requested_item":{"zipcode": "33777", "address": "8121 Norwood Rd"},
"errors":[],
"changes":["State added or changed", "Locality (city, municipality) added or changed"],
"details":["Address fully verified"],
"match": true
},
"city": "Seminole",
"county_fips": "12103",
"geo_precision": "rooftop",
"block_id": "121030250131007",
"zipcode": "33777",
"blockgroup_id": "121030250131",
"address_full": "8121 Norwood Rd Seminole FL 33777",
"state": "FL",
"msa": "45300",
"metrodiv": null,
"unit": null,
"address": "8121 Norwood Rd",
"lat": 27.85092,
"lng": -82.75181,
"slug": "8121-Norwood-Rd-Seminole-FL-33777",
"zipcode_plus4": "3543"
}
}
]

Hello,

If you go to this website you can see your data in a neat way so that you can find which values you want to store and how to get to them.


For example if I wanted to insert slug property that I have highlighted in the picture above to a database, you would get it with (see bold text):

//BACK END CODE:
// Filename: backend/sendEmail.jsw  (web modules need to have a *.jsw* extension)
import { fetch } from 'wix-fetch';
import wixData from 'wix-data';
// wix-fetch is the API we provide to make https calls in the backend
//const user = "xxxx";
//const pass = "xxxx"
const api_key_id = 'xxxxx';
const api_key_secret = xxxxx';
export function sendOrder(address, zipcode, file) {
                return fetch('https://api.housecanary.com/v2/property/sales_history', {
                  body: JSON.stringify([{ "address": address, "zipcode": zipcode }]),
                  headers: {
    Authorization: "Basic xxxxxx
    'Content-Type': "application/json",
                  },
                  method: 'post',
  })
  .then((res) => res.json())
  .then((data) => {
      console.log(data);
      //An example of how to get a certain property, can get as many as you want
      let slug = data[0].address_info.slug
      let toInsert = {
          'slug': slug
          //Add other data you want to store here
      }
      wixData.insert("myCollection", toInsert)
          .then((results) => {
              console.log(results); //see if it inserted
          })
          .catch((err) => {
              console.log(err); //see if error occured          
          });
   })

Hope this helps,
Majd

Awesome!! Thank you Sooooo much.

Hello Majd. Thank you again. I was able to insert data. I have one quick question. The ‘result’ item is an array. What would a for each on that item look like? Would like this to happen in my backend jsw file. Thanks again.

Hello Eddie,

If you are looking to store everything from the request, a good way to do this would be to insert them this way:

wixData.insert("myCollection", data[0].address_info.statues)
  .then((record) => {
    console.log(`record inserted: ${record}`);
    wixData.insert("myCollection", data[0]['property/sales_history']).then((rec)         => console.log(`rec inserted: ${rec}`));
  }).catch((err) => {
    console.log(err, "see error if there is here")
  });

This is assuming that the property/sales_history property doesn’t have anything nested in it, as we want it to be the same format as address_info.statues (no nesting)

Hope this helps,
Majd

Thanks again Majd. That did insert all property/sales_history into my collection, however the data I am needing is an array object called ‘result’ nested in property/sales_history. I think what I will try is an after insert hook on the collection take the ‘result’ column and loop through the array and insert into another collection. Does this sound like a possibility? Thank you.

Ah it seems I misunderstood the first time. This should do it for you:

//Get The results array
const resultArray = [...data[0]['property/sales_history'].result];

//For each item in the results array, insert it into the toInsert Object
//The toInsert object will be inserted only once
resultArray.forEach((item) => {
    toInsert[item] = item;
});

Add this before you insert the toInsert object into your collection.

Hope this helps,
Majd

Thanks Majd. I am having a bit of a problem understanding as you can see below.

import { fetch } from ‘wix-fetch’;
import wixData from ‘wix-data’;
// wix-fetch is the API we provide to make https calls in the backend
const api_key_id = ‘XXXXXXXX’;
const api_key_secret = ‘XXXXXXXX’;
export function sendOrder(address, zipcode, file) {
return fetch(’ https://api.housecanary.com/v2/property/sales_history ', {
body: JSON.stringify([{ “address”: address, “zipcode”: zipcode }]),
headers: {
Authorization: “Basic XXXXXXXXX”,
‘Content-Type’: “application/json”,
},
method: ‘post’,
})
.then((result) => result.json())
//.then((result) => console.log(result))
.then((data) => {
console.log(data)
const resultArray = […data[0][‘property/sales_history’].result];
resultArray.forEach((item) => {
toInsert[item] = item;
});
let toInsert = {
‘fips’: fips,
‘event’: event,
‘apn’: apn,
‘grantee1’: grantee1,
‘grantee2’: grantee2,
‘grantor2’: grantor2,
‘page’: page,
‘grantor2Fore’: grantor2fore,
‘amount’: amount,
‘grantee1Fore’: grantee1fore,
‘date’: date,
‘grantee2Fore’: grantee2fore,
‘grantor1’: grantor1,
‘doc’: doc,
‘book’: book,
‘grantor1Fore’: grantor1fore
wixData.insert(“SalesHistory”, toInsert)
.then((results) => {
console.log(results); //see if it inserted
})
. catch ((err) => {
console.log(err); //see if error occured
});
});
}

Hello Majd still struggling to understand your last post. I AM SO CLOSE!!. I thought the following made sense, but no chance. Could use your knowledge when you get a chance. hank you.

// Filename: backend/sendEmail.jsw (web modules need to have a .jsw extension)
import { fetch } from ‘wix-fetch’;
import wixData from ‘wix-data’;
// wix-fetch is the API we provide to make https calls in the backend
export function sendOrder(address, zipcode, file) {
return fetch(’ https://api.housecanary.com/v2/property/sales_history ', {
body: JSON.stringify([{ “address”: address, “zipcode”: zipcode }]),
headers: {
Authorization: "Basic xxxxxxxxxxxxxxxxx”
‘Content-Type’: “application/json”,
},
method: ‘post’,
})
.then((result) => result.json())
//.then((result) => console.log(result))
.then((data) => {
console.log(data)
const resultArray = [
title = data[0][‘property/sales_history’].result.apn,
fips = data[0][‘property/sales_history’].result.fips,
event_type = data[0][‘property/sales_history’].result.event_type,
apn = data[0][‘property/sales_history’].result.apn,
grantee1 = data[0][‘property/sales_history’].result.grantee_1,
grantee2 = data[0][‘property/sales_history’].result.grantee_2,
grantor2 = data[0][‘property/sales_history’].result.grantor_2,
record_page = data[0][‘property/sales_history’].result.record_page,
grantor2fore = data[0][‘property/sales_history’].result.grantor_2_forenames,
amount = data[0][‘property/sales_history’].result.amount,
grantee1fore = data[0][‘property/sales_history’].result.grantee_1_forenames,
record_date = data[0][‘property/sales_history’].result.record_date,
grantee2fore = data[0][‘property/sales_history’].result.grantee_2_forenames,
grantor1 = data[0][‘property/sales_history’].result.grantor_1,
record_doc = data[0][‘property/sales_history’].result.record_doc,
record_book = data[0][‘property/sales_history’].result.record_book,
grantor1fore = data[0][‘property/sales_history’].result.grantor_1_forenames
];
let title = title
let fips = fips
let event_type = event_type
let apn = apn;
let grantee1 = grantee1;
let grantee2 = grantee2;
let grantor2 = grantor2;
let record_page = record_page;
let grantor2fore = grantor2fore;
let amount = amount;
let grantee1fore = grantee1fore;
let record_date = record_date;
let grantee2fore = grantee2fore;
let grantor1 = grantor1;
let record_doc = record_doc;
let record_book = record_book;
let grantor1fore = grantor1fore
let toInsert = {
‘title’: title,
‘fips’: fips,
‘event’: event_type,
‘apn’: apn,
‘grantee1’: grantee1,
‘grantee2’: grantee2,
‘grantor2’: grantor2,
‘page’: record_page,
‘grantor2Fore’: grantor2fore,
‘amount’: amount,
‘grantee1Fore’: grantee1fore,
‘date’: record_date,
‘grantee2Fore’: grantee2fore,
‘grantor1’: grantor1,
‘doc’: record_doc,
‘book’: record_book,
‘grantor1Fore’: grantor1fore
}
resultArray.forEach((item) => {
toInsert[item] = item;
wixData.insert(“SalesHistory”, toInsert)
}).then((results) => {
console.log(results); //see if it inserted
})
.catch((err) => {
console.log(err); //see if error occured
});
});
}

Try this out, you have some syntax errors that I fixed a bit.

 
// Filename: backend/sendEmail.jsw  (web modules need to have a *.jsw* extension)
import { fetch } from 'wix-fetch';
import wixData from 'wix-data';
// wix-fetch is the API we provide to make https calls in the backend
export function sendOrder(address, zipcode, file) {
                return fetch('https://api.housecanary.com/v2/property/sales_history', {
                  body: JSON.stringify([{ "address": address, "zipcode": zipcode }]),
                  headers: {
    Authorization: "Basic xxxxxxxxxxxxxxxxx”
    'Content-Type': "application/json",
                  },
                  method: 'post',
  })
  .then((result) => result.json())
  //.then((result) => console.log(result))
  .then((data) => {
                  console.log(data)
                  const resultArray = [
    title = data[0]['property/sales_history'].result.apn,
    fips = data[0]['property/sales_history'].result.fips,
    event_type = data[0]['property/sales_history'].result.event_type,
    apn = data[0]['property/sales_history'].result.apn,
    grantee1 = data[0]['property/sales_history'].result.grantee_1,
    grantee2 = data[0]['property/sales_history'].result.grantee_2,
    grantor2 = data[0]['property/sales_history'].result.grantor_2,
    record_page = data[0]['property/sales_history'].result.record_page,
    grantor2fore = data[0]['property/sales_history'].result.grantor_2_forenames,
    amount = data[0]['property/sales_history'].result.amount,
    grantee1fore = data[0]['property/sales_history'].result.grantee_1_forenames,
    record_date = data[0]['property/sales_history'].result.record_date,
    grantee2fore = data[0]['property/sales_history'].result.grantee_2_forenames,
    grantor1 = data[0]['property/sales_history'].result.grantor_1,
    record_doc = data[0]['property/sales_history'].result.record_doc,
    record_book = data[0]['property/sales_history'].result.record_book,
    grantor1fore = data[0]['property/sales_history'].result.grantor_1_forenames
                  ];
                  
                  let toInsert = {};
                  resultArray.forEach((item) => {     
                         toInsert[item] = item; 
                  }); 
                  
                  wixData.insert("SalesHistory", toInsert )
                    .then((inserted)=> {
                    console.log('inserted: ', inserted);
                    })
    }).then((results) => {
                    console.log(results); //see if it inserted
    })
    .catch((err) => {
                    console.log(err); //see if error occured 
    });
  });
}