-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathus_zipcode.mjs
More file actions
63 lines (49 loc) · 1.81 KB
/
us_zipcode.mjs
File metadata and controls
63 lines (49 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import SmartySDK from "smartystreets-javascript-sdk";
const SmartyCore = SmartySDK.core;
const Lookup = SmartySDK.usZipcode.Lookup;
// for client-side requests (browser/mobile), use this code:
// let key = process.env.SMARTY_EMBEDDED_KEY;
// const credentials = new SmartyCore.SharedCredentials(key);
// for Server-to-server requests, use this code:
let authId = process.env.SMARTY_AUTH_ID;
let authToken = process.env.SMARTY_AUTH_TOKEN;
const credentials = new SmartyCore.BasicAuthCredentials(authId, authToken);
let clientBuilder = new SmartyCore.ClientBuilder(credentials);
// .withBaseUrl("YOUR URL") // withBaseUrl() should be used if you are self-hosting the Smarty API
let client = clientBuilder.buildUsZipcodeClient();
// Documentation for input fields can be found at:
// https://www.smarty.com/docs/us-zipcode-api#input-fields
let lookup1 = new Lookup();
lookup1.inputId = "01189998819991197253"; // Optional ID from your system
lookup1.zipCode = "49786";
let lookup2 = new Lookup();
lookup2.inputId = "dfc33cb6-829e-4fea-aa1b-b6d6580f0817";
lookup2.city = "Provo";
lookup2.state = "UT";
lookup2.zipCode = "84604";
let lookup3 = new Lookup();
lookup3.city = "Phoenix";
lookup3.state = "AZ";
// uncomment the following line to add a custom parameter
// lookup3.addCustomParameter("input_id", 1234);
let batch = new SmartyCore.Batch();
batch.add(lookup1);
batch.add(lookup2);
batch.add(lookup3);
await handleResponse(batch);
function viewResults(response) {
response.lookups.map((lookup) =>
lookup.result.map((candidate) => {
candidate.cities.map((city) => console.log(city.city));
// candidate.zipcodes.map(zipcode => console.log(zipcode.zipcode));
}),
);
}
async function handleResponse(lookup) {
try {
const result = await client.send(lookup);
viewResults(result);
} catch (err) {
console.log(err);
}
}