-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode-packstation.js
97 lines (87 loc) · 2.4 KB
/
node-packstation.js
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const fetch = require("node-fetch")
/**
* Checks if a given string is numerical
* @param { string } str - the string to be checked
* @returns { boolean }
*/
const isAllNum = (str) => {
return (
typeof str === 'string' &&
/^\d+$/.test(str)
)
}
/**
* Checks if a given string is a valid number for a Packstation
* @param { string } packstationNumber
* @returns { boolean }
*/
const isValidPackstationNumber = (packstationNumber) => {
return (
isAllNum(packstationNumber) &&
packstationNumber.length === 3
)
}
/**
* Checks if a given string is a german zip code
* @param { string } zipCode
* @returns { boolean }
*/
const isValidZipCode = (zipCode) => {
return (
isAllNum(zipCode) &&
zipCode.length === 5
)
}
/**
* Retrieve the json with addresses of Packstationen in the range of the zipCode
* @param { string } zipCode - german zip code
* @returns { Promise < object > } returns the javascript representation of the json returned from the api
*/
const getAddressList = async (zipCode) => {
if ( ! isValidZipCode(zipCode) ) {
throw new Error("ZIPCODE ERROR: invalid input zipcode")
}
const url = `https://www.dhl.de/int-postfinder/postfinder_webservice/rest/v1/nearbySearch?address=${zipCode}&locationType=PACKSTATION`
try {
const response = await fetch(url)
const addressList = await response.json()
return addressList
} catch (error) {
throw new Error(`API-ERROR: couldn't gather the list of Packstation\nActual Error: ${error}`)
}
}
/**
* Checks if a pair of PackstationNumber and zipCode match to a valid address.
* @param { string } zipCode - german zip code of the Packstation
* @param { string } packstationNumber - number of the Packstation
* @returns { Promise < boolean > }
*/
const isValidAddress = async (zipCode, packstationNumber) => {
if (
! isValidZipCode(zipCode) ||
! isValidPackstationNumber(packstationNumber)
) {
return false
}
try {
const addressList = await getAddressList(zipCode)
for (let ps of addressList.pfLocations) {
if (ps.primaryKeyZipRegion
&& ps.primaryKeyZipRegion === packstationNumber
&& ps.zipCode
&& ps.zipCode === zipCode
) {
return true
}
}
return false
} catch (error) {
console.log(error)
}
}
module.exports = {
listAddresses: getAddressList,
isValidAddress,
isValidZipCode,
isValidPackstationNumber
}