Here is an example of how to verify addresses on Import. This hook example is formatted for Portal 2.0.
import FlatfileImporter from "@flatfile/adapter";
import $ from "jquery";
import { schemas } from "./schemas";
const { contactSchema } = schemas;
// free SmartyStreets trial account limited to 1,000 lookups/month
const apiToken = "XXXXXXXXXXXXXXXXXXXXX";
const importer = new FlatfileImporter(
"LICENSEKEY",
contactSchema
);
importer.setCustomer({
userId: "19234",
name: "Foo Bar"
});
importer.registerStepHook("review", ({ headers_matched }) => {
// review stephook happens right before the data goes to the review page
importer.addVirtualField(
{
label: "Valid Address?",
key: "validAddress",
type: "checkbox"
},
{
order: 6
}
);
});
importer.registerRecordHook(async (record, index, mode) => {
letout={};
// name splitting example: splits full names in the first name field
if(record.firstName&&!record.lastName){
if(record.firstName.includes("")){
constcomponents=record.firstName.split("");
out.firstName={ value:components.shift()};
out.lastName={ value:components.join("")};
}
}
if(record.address1&&record.city&&record.state&&record.zipCode){
constaddress=`street=${encodeURI(record.address1)}&street2=${encodeURI(
record.address2
)}&city=${encodeURI(record.city)}&state=${encodeURI(
record.state
)}&zipcode=${encodeURI(record.zipCode)}&key=${apiToken}`;
asyncfunctionmyFetch(){
try{
// make api call to smartystreets to validate address
letresponse=awaitfetch(
"https://us-street.api.smartystreets.com/street-address?license=us-core-cloud&"+
address,
{
method: "GET",
headers: {
"Content-Type":"application/json"
}
}
);
if(!response.ok){
thrownewError(`HTTP error! status: ${response.status}`);
}else{
// We have a 2XX response from smartysteets
letmyRes=awaitresponse.json();
if(myRes.length>0){
// if payload exists, then address is valid
out.validAddress={ value:true};
}else{
// empty payload means invalid address
out.validAddress={ value:false};
}
}
}catch(e){
console.log(e);
}
}
awaitmyFetch();
}
returnout;
});
$("#launch").click(function () {
importer
.requestDataFromUser()
.then(function(results){
importer.displaySuccess("Thanks for your data.");
$("#raw_output").text(JSON.stringify(results.data,"",2));
})
.catch(function(error){
console.info(error||"window close");
});
});
Comments
0 comments
Please sign in to leave a comment.