-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
107 lines (98 loc) · 2.13 KB
/
index.ts
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
98
99
100
101
102
103
104
105
106
107
import fetch from "node-fetch";
const VERSION = "2.0.38";
const ZIPCODE_URL = `https://marocchino.github.io/jipcode/${VERSION}`;
type Option = {
prefectureCode?: boolean;
};
type Zipcode = {
zipcode: string;
prefecture: string;
prefectureCode?: number;
city: string;
town: string;
};
export const prefectureCode: { [key: string]: number } = {
北海道: 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,
徳島県: 37,
香川県: 37,
愛媛県: 38,
高知県: 39,
福岡県: 40,
佐賀県: 41,
長崎県: 42,
熊本県: 43,
大分県: 44,
宮崎県: 45,
鹿児島県: 46,
沖縄県: 47,
};
export const locate = async (
zipcode: string,
option: Option = {}
): Promise<Zipcode[]> => {
zipcode = zipcode.replace(/\D/g, "");
if (zipcode.length !== 7 || !/^\d+$/.test(zipcode)) {
return [];
}
const url = `${ZIPCODE_URL}/${zipcode.slice(0, 3)}.csv.json`;
// get json
try {
const response = await fetch(url);
const json = (await response.json()) as string[][];
const addressesArray = json.filter((address) => address[0] === zipcode);
if (option.prefectureCode) {
return addressesArray.map(extendedAddressFrom);
} else {
return addressesArray.map(basicAddressFrom);
}
} catch (e) {
return [];
}
};
const basicAddressFrom = (address: string[]): Zipcode => ({
zipcode: address[0],
prefecture: address[1],
city: address[2],
town: address[3],
});
const extendedAddressFrom = (address: string[]): Zipcode => {
const basic = basicAddressFrom(address);
return {
...basic,
prefectureCode: prefectureCode[basic.prefecture],
};
};