jp-postal-lookup 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +451 -2
- package/index.d.ts +158 -0
- package/package.json +40 -4
- package/src/index.cjs +191 -0
- package/src/index.js +297 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dungdao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,452 @@
|
|
|
1
|
-
#
|
|
1
|
+
# jp-postal-lookup 📮
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/jp-postal-lookup)
|
|
4
|
+
[](https://nodejs.org/)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
[](package.json)
|
|
7
|
+
[](index.d.ts)
|
|
8
|
+
|
|
9
|
+
> **Zero-dependency** Japanese address and postal code lookup library powered by [HeartRails Geo API](https://geoapi.heartrails.com/).
|
|
10
|
+
> Tra cứu địa chỉ và mã bưu điện Nhật Bản gọn nhẹ, hỗ trợ **ESM**, **CommonJS**, **TypeScript**, **Node.js 18+** và **Trình duyệt (Browser)**.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 📑 Mục lục (Table of Contents)
|
|
15
|
+
|
|
16
|
+
1. [Yêu cầu môi trường (System Requirements)](#-yêu-cầu-môi-trường-system-requirements)
|
|
17
|
+
2. [Cài đặt (Installation)](#-cài-đặt-installation)
|
|
18
|
+
3. [Bắt đầu nhanh (Quick Start)](#-bắt-đầu-nhanh-quick-start)
|
|
19
|
+
4. [Tích hợp vào Frameworks](#-tích-hợp-vào-frameworks)
|
|
20
|
+
- [Vue 3 / Nuxt 3](#1-vue-3--nuxt-3)
|
|
21
|
+
- [React / Next.js](#2-react--nextjs)
|
|
22
|
+
- [Node.js (Express / Backend)](#3-nodejs-backend-express)
|
|
23
|
+
- [Thay thế `getAddress.js` cũ](#4-thay-thế-file-getaddressjs-sẵn-có)
|
|
24
|
+
5. [Tài liệu API chi tiết (API Reference)](#-tài-liệu-api-chi-tiết-api-reference)
|
|
25
|
+
- [Modern Promise API](#modern-promise-api)
|
|
26
|
+
- [Legacy Compatible API](#legacy-compatible-api)
|
|
27
|
+
- [Kiểu dữ liệu (TypeScript Interfaces)](#kiểu-dữ-liệu-typescript-interfaces)
|
|
28
|
+
6. [Kiểm thử (Testing)](#-kiểm-thử-testing)
|
|
29
|
+
7. [Xử lý lỗi & Lưu ý (Error Handling & Gotchas)](#-xử-lý-lỗi--lưu-ý-error-handling--gotchas)
|
|
30
|
+
8. [Hướng dẫn Publish lên npm](#-hướng-dẫn-publish-lên-npm)
|
|
31
|
+
9. [License](#-license)
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## 💻 Yêu cầu môi trường (System Requirements)
|
|
36
|
+
|
|
37
|
+
| Môi trường | Phiên bản hỗ trợ | Ghi chú |
|
|
38
|
+
| :--- | :--- | :--- |
|
|
39
|
+
| **Node.js** | `>= 18.0.0` (Khuyến nghị: 18.x, 20.x, 22.x LTS) | Sử dụng `globalThis.fetch` tích hợp sẵn trong Node.js |
|
|
40
|
+
| **Trình duyệt** | Chrome 66+, Firefox 57+, Safari 11.1+, Edge 79+ | Hỗ trợ Fetch API & ES6 Modules |
|
|
41
|
+
| **TypeScript** | `>= 4.5.0` | Sẵn file `index.d.ts` với đầy đủ autocomplete & types |
|
|
42
|
+
| **Package Managers** | npm 7+, yarn 1/3+, pnpm 7+, bun 1+ | Hỗ trợ `exports` map trong package.json |
|
|
43
|
+
| **Dependencies** | **0 dependencies** | Không cần cài đặt axios, lodash hay bất kỳ thư viện bên ngoài nào |
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## 📦 Cài đặt (Installation)
|
|
48
|
+
|
|
49
|
+
### 1. Từ npm registry:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
# npm
|
|
53
|
+
npm install jp-postal-lookup
|
|
54
|
+
|
|
55
|
+
# yarn
|
|
56
|
+
yarn add jp-postal-lookup
|
|
57
|
+
|
|
58
|
+
# pnpm
|
|
59
|
+
pnpm add jp-postal-lookup
|
|
60
|
+
|
|
61
|
+
# bun
|
|
62
|
+
bun add jp-postal-lookup
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### 2. Cài đặt trực tiếp từ local directory (dành cho monorepo hoặc phát triển nội bộ):
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
# Cài đường dẫn trực tiếp từ thư mục
|
|
69
|
+
npm install /home/dungdao/projects/jp-postal-lookup
|
|
70
|
+
|
|
71
|
+
# Hoặc dùng npm link
|
|
72
|
+
cd /home/dungdao/projects/jp-postal-lookup
|
|
73
|
+
npm link
|
|
74
|
+
|
|
75
|
+
cd /path/to/your-project
|
|
76
|
+
npm link jp-postal-lookup
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### 3. Sử dụng trực tiếp trên Browser (CDN):
|
|
80
|
+
|
|
81
|
+
```html
|
|
82
|
+
<script type="module">
|
|
83
|
+
import { searchAddressByPostal } from 'https://esm.sh/jp-postal-lookup';
|
|
84
|
+
|
|
85
|
+
const address = await searchAddressByPostal('100-0001');
|
|
86
|
+
console.log(address); // "東京都千代田区千代田"
|
|
87
|
+
</script>
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## ⚡ Bắt đầu nhanh (Quick Start)
|
|
93
|
+
|
|
94
|
+
### ES Module (`import`)
|
|
95
|
+
|
|
96
|
+
```javascript
|
|
97
|
+
import { searchAddressByPostal, searchPostalByAddress } from 'jp-postal-lookup';
|
|
98
|
+
|
|
99
|
+
// 1. Tìm địa chỉ theo mã bưu điện (tự chuẩn hóa '100-0001', '100ー0001' -> '1000001')
|
|
100
|
+
const address = await searchAddressByPostal('100-0001');
|
|
101
|
+
console.log(address);
|
|
102
|
+
// Output: "東京都千代田区千代田"
|
|
103
|
+
|
|
104
|
+
// 2. Tìm mã bưu điện theo tên địa chỉ
|
|
105
|
+
const postal = await searchPostalByAddress('千代田区千代田');
|
|
106
|
+
console.log(postal);
|
|
107
|
+
// Output: "1000001"
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### CommonJS (`require`)
|
|
111
|
+
|
|
112
|
+
```javascript
|
|
113
|
+
const { searchAddressByPostal, onSearchAddressByPostcode } = require('jp-postal-lookup');
|
|
114
|
+
|
|
115
|
+
async function run() {
|
|
116
|
+
const address = await searchAddressByPostal('100-0001');
|
|
117
|
+
console.log('Address:', address);
|
|
118
|
+
}
|
|
119
|
+
run();
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## 🧩 Tích hợp vào Frameworks
|
|
125
|
+
|
|
126
|
+
### 1. Vue 3 / Nuxt 3
|
|
127
|
+
|
|
128
|
+
```vue
|
|
129
|
+
<template>
|
|
130
|
+
<div class="address-lookup">
|
|
131
|
+
<input
|
|
132
|
+
v-model="postalCode"
|
|
133
|
+
placeholder="100-0001"
|
|
134
|
+
@blur="handleLookup"
|
|
135
|
+
/>
|
|
136
|
+
<button :disabled="loading" @click="handleLookup">
|
|
137
|
+
{{ loading ? 'Đang tìm...' : 'Tìm địa chỉ' }}
|
|
138
|
+
</button>
|
|
139
|
+
<p v-if="address">Địa chỉ: {{ address }}</p>
|
|
140
|
+
<p v-if="error" class="error">{{ error }}</p>
|
|
141
|
+
</div>
|
|
142
|
+
</template>
|
|
143
|
+
|
|
144
|
+
<script setup>
|
|
145
|
+
import { ref } from 'vue';
|
|
146
|
+
import { searchAddressByPostal } from 'jp-postal-lookup';
|
|
147
|
+
|
|
148
|
+
const postalCode = ref('');
|
|
149
|
+
const address = ref('');
|
|
150
|
+
const error = ref('');
|
|
151
|
+
const loading = ref(false);
|
|
152
|
+
|
|
153
|
+
const handleLookup = async () => {
|
|
154
|
+
if (!postalCode.value) return;
|
|
155
|
+
loading.value = true;
|
|
156
|
+
error.value = '';
|
|
157
|
+
try {
|
|
158
|
+
const result = await searchAddressByPostal(postalCode.value);
|
|
159
|
+
if (result) {
|
|
160
|
+
address.value = result;
|
|
161
|
+
} else {
|
|
162
|
+
error.value = 'Không tìm thấy địa chỉ cho mã bưu điện này.';
|
|
163
|
+
}
|
|
164
|
+
} catch (err) {
|
|
165
|
+
error.value = 'Lỗi kết nối API: ' + err.message;
|
|
166
|
+
} finally {
|
|
167
|
+
loading.value = false;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
</script>
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### 2. React / Next.js
|
|
174
|
+
|
|
175
|
+
```tsx
|
|
176
|
+
import React, { useState } from 'react';
|
|
177
|
+
import { searchAddressByPostal, type GeoLocation } from 'jp-postal-lookup';
|
|
178
|
+
|
|
179
|
+
export function AddressForm() {
|
|
180
|
+
const [postal, setPostal] = useState('');
|
|
181
|
+
const [location, setLocation] = useState<GeoLocation | null>(null);
|
|
182
|
+
|
|
183
|
+
const onSearch = async () => {
|
|
184
|
+
// Lấy thông tin chi tiết (tỉnh, thành phố, toạ độ x, y)
|
|
185
|
+
const data = await searchAddressByPostal(postal, { raw: true });
|
|
186
|
+
setLocation(data);
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
return (
|
|
190
|
+
<div>
|
|
191
|
+
<input
|
|
192
|
+
value={postal}
|
|
193
|
+
onChange={(e) => setPostal(e.target.value)}
|
|
194
|
+
placeholder="100-0001"
|
|
195
|
+
/>
|
|
196
|
+
<button onClick={onSearch}>Tra cứu</button>
|
|
197
|
+
{location && (
|
|
198
|
+
<div>
|
|
199
|
+
<p>Tỉnh: {location.prefecture}</p>
|
|
200
|
+
<p>Quận/Huyện: {location.city}</p>
|
|
201
|
+
<p>Phường/Xã: {location.town}</p>
|
|
202
|
+
</div>
|
|
203
|
+
)}
|
|
204
|
+
</div>
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### 3. Node.js Backend (Express)
|
|
210
|
+
|
|
211
|
+
```javascript
|
|
212
|
+
import express from 'express';
|
|
213
|
+
import { searchAddressByPostal } from 'jp-postal-lookup';
|
|
214
|
+
|
|
215
|
+
const app = express();
|
|
216
|
+
|
|
217
|
+
app.get('/api/lookup-postal', async (req, res) => {
|
|
218
|
+
const { code } = req.query;
|
|
219
|
+
if (!code) {
|
|
220
|
+
return res.status(400).json({ error: 'Missing postal code' });
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const address = await searchAddressByPostal(code, { raw: true });
|
|
224
|
+
if (!address) {
|
|
225
|
+
return res.status(404).json({ message: 'Address not found' });
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return res.json({ data: address });
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
app.listen(3000, () => console.log('Server running on port 3000'));
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### 4. Thay thế file `getAddress.js` sẵn có
|
|
235
|
+
|
|
236
|
+
Nếu dự án của bạn đang dùng file tiện ích cũ `src/utilities/getAddress.js`, bạn chỉ cần thay đổi đường dẫn import:
|
|
237
|
+
|
|
238
|
+
```diff
|
|
239
|
+
- import { onSearchAddressByPostcode, onSearchPostcodeByAddress } from '@/utilities/getAddress.js';
|
|
240
|
+
+ import { onSearchAddressByPostcode, onSearchPostcodeByAddress } from 'jp-postal-lookup';
|
|
241
|
+
```
|
|
242
|
+
Toàn bộ tham số, kiểu trả về và callback vẫn giữ nguyên 100%, không cần thay đổi bất kỳ dòng code logic nào khác!
|
|
243
|
+
|
|
244
|
+
---
|
|
245
|
+
|
|
246
|
+
## 📖 Tài liệu API chi tiết (API Reference)
|
|
247
|
+
|
|
248
|
+
### Modern Promise API
|
|
249
|
+
|
|
250
|
+
#### 1. `searchAddressByPostal(postal, options?)`
|
|
251
|
+
Tra cứu địa chỉ theo mã bưu điện.
|
|
252
|
+
|
|
253
|
+
- **Tham số**:
|
|
254
|
+
- `postal` (`string | number`): Mã bưu điện Nhật Bản (VD: `'100-0001'`, `'1000001'`, `'100ー0001'`).
|
|
255
|
+
- `options` (`object`, tùy chọn):
|
|
256
|
+
- `raw` (`boolean`, mặc định: `false`): Nếu `true`, trả về `GeoLocation` object gồm toạ độ x, y, kana.
|
|
257
|
+
- `all` (`boolean`, mặc định: `false`): Nếu `true`, trả về mảng `GeoLocation[]` tất cả các địa chỉ khớp.
|
|
258
|
+
- `baseUrl` (`string`, tùy chọn): Thay đổi endpoint API nếu dùng proxy hoặc mock server.
|
|
259
|
+
- **Giá trị trả về**: `Promise<string | GeoLocation | GeoLocation[] | null>`
|
|
260
|
+
|
|
261
|
+
```javascript
|
|
262
|
+
// Trả về chuỗi địa chỉ
|
|
263
|
+
const str = await searchAddressByPostal('100-0001');
|
|
264
|
+
// "東京都千代田区千代田"
|
|
265
|
+
|
|
266
|
+
// Trả về object chi tiết
|
|
267
|
+
const obj = await searchAddressByPostal('100-0001', { raw: true });
|
|
268
|
+
// {
|
|
269
|
+
// postal: "1000001",
|
|
270
|
+
// prefecture: "東京都",
|
|
271
|
+
// city: "千代田区",
|
|
272
|
+
// town: "千代田",
|
|
273
|
+
// city_kana: "ちよだく",
|
|
274
|
+
// town_kana: "ちよだ",
|
|
275
|
+
// x: "139.7533",
|
|
276
|
+
// y: "35.6852"
|
|
277
|
+
// }
|
|
278
|
+
|
|
279
|
+
// Trả về danh sách nếu mã bưu điện map tới nhiều phường
|
|
280
|
+
const list = await searchAddressByPostal('100-0001', { all: true });
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
---
|
|
284
|
+
|
|
285
|
+
#### 2. `searchPostalByAddress(address, options?)`
|
|
286
|
+
Tra cứu mã bưu điện theo từ khóa địa chỉ.
|
|
287
|
+
|
|
288
|
+
- **Tham số**:
|
|
289
|
+
- `address` (`string`): Tên địa chỉ (VD: `'千代田区千代田'`).
|
|
290
|
+
- `options` (`object`, tùy chọn):
|
|
291
|
+
- `raw` (`boolean`, mặc định: `false`): Trả về `GeoLocation` object.
|
|
292
|
+
- `all` (`boolean`, mặc định: `false`): Trả về mảng `GeoLocation[]`.
|
|
293
|
+
- `matching` (`'prefix' | 'suffix' | 'like'`, mặc định: `'suffix'`).
|
|
294
|
+
- **Giá trị trả về**: `Promise<string | GeoLocation | GeoLocation[] | null>`
|
|
295
|
+
|
|
296
|
+
```javascript
|
|
297
|
+
const postal = await searchPostalByAddress('千代田区千代田');
|
|
298
|
+
// "1000001"
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
---
|
|
302
|
+
|
|
303
|
+
#### 3. `getAreas()`
|
|
304
|
+
Lấy danh sách các vùng chính của Nhật Bản.
|
|
305
|
+
- **Giá trị trả về**: `Promise<string[]>`
|
|
306
|
+
- **Kết quả**: `['北海道', '東北', '関東', '中部', '近畿', '中国', '四国', '九州']`
|
|
307
|
+
|
|
308
|
+
---
|
|
309
|
+
|
|
310
|
+
#### 4. `getPrefectures(area)`
|
|
311
|
+
Lấy danh sách các tỉnh theo vùng.
|
|
312
|
+
- **Tham số**: `area` (`string`): VD: `'関東'`.
|
|
313
|
+
- **Giá trị trả về**: `Promise<string[]>`
|
|
314
|
+
- **Kết quả**: `['茨城県', '栃木県', '群馬県', '埼玉県', '千葉県', '東京都', '神奈川県']`
|
|
315
|
+
|
|
316
|
+
---
|
|
317
|
+
|
|
318
|
+
#### 5. `getCities(prefecture, area?)`
|
|
319
|
+
Lấy danh sách các thành phố/quận/huyện thuộc tỉnh.
|
|
320
|
+
- **Tham số**:
|
|
321
|
+
- `prefecture` (`string`): Tên tỉnh (VD: `'東京都'`).
|
|
322
|
+
- `area` (`string`, tùy chọn).
|
|
323
|
+
- **Giá trị trả về**: `Promise<string[]>`
|
|
324
|
+
- **Kết quả**: `['千代田区', '中央区', '港区', '新宿区', ...]`
|
|
325
|
+
|
|
326
|
+
---
|
|
327
|
+
|
|
328
|
+
#### 6. `getTowns(city, prefecture?)`
|
|
329
|
+
Lấy danh sách phường/thị trấn thuộc quận/thành phố.
|
|
330
|
+
- **Tham số**:
|
|
331
|
+
- `city` (`string`): Tên quận/huyện (VD: `'千代田区'`).
|
|
332
|
+
- `prefecture` (`string`, tùy chọn): Tên tỉnh (VD: `'東京都'`).
|
|
333
|
+
- **Giá trị trả về**: `Promise<string[]>`
|
|
334
|
+
- **Kết quả**: `['丸の内', '大手町', '一ツ橋', ...]`
|
|
335
|
+
|
|
336
|
+
---
|
|
337
|
+
|
|
338
|
+
#### 7. `normalizePostal(postal)`
|
|
339
|
+
Hàm tiện ích loại bỏ ký tự không hợp lệ trong zip code.
|
|
340
|
+
- **Tham số**: `postal` (`string | number`)
|
|
341
|
+
- **Kết quả**:
|
|
342
|
+
- `normalizePostal('100-0001')` ➜ `'1000001'`
|
|
343
|
+
- `normalizePostal(' 100ー0001 ')` ➜ `'1000001'`
|
|
344
|
+
- `normalizePostal('100 0001')` ➜ `'1000001'`
|
|
345
|
+
|
|
346
|
+
---
|
|
347
|
+
|
|
348
|
+
### Legacy Compatible API (Tương thích `getAddress.js`)
|
|
349
|
+
|
|
350
|
+
| Tên hàm | Chữ ký | Mô tả |
|
|
351
|
+
| :--- | :--- | :--- |
|
|
352
|
+
| `onSearchAddressByPostcode(postcode, isResponse?)` | `(string\|number, boolean?) => Promise<string \| GeoLocation \| null>` | `isResponse=false` trả về chuỗi địa chỉ; `isResponse=true` trả về object |
|
|
353
|
+
| `onSearchPostcodeByAddress(address, isResponse?, matching?)` | `(string, boolean?, string?) => Promise<string \| GeoLocation \| null>` | Tìm zip code theo chuỗi địa chỉ |
|
|
354
|
+
| `getPrefecturesByArea(area, callback?)` | `(string, (res) => void) => Promise<object>` | Lấy danh sách tỉnh, hỗ trợ callback |
|
|
355
|
+
| `onGetCitiesByPrefecture(area, prefecture, callback?)` | `(string, string, (res) => void) => Promise<object>` | Lấy danh sách quận/huyện |
|
|
356
|
+
| `onGetTownsByCity(city, prefecture, callback?)` | `(string, string, (res) => void) => Promise<object>` | Lấy danh sách phường/xã |
|
|
357
|
+
|
|
358
|
+
---
|
|
359
|
+
|
|
360
|
+
### Kiểu dữ liệu (TypeScript Interfaces)
|
|
361
|
+
|
|
362
|
+
```typescript
|
|
363
|
+
export interface GeoLocation {
|
|
364
|
+
city: string; // "千代田区"
|
|
365
|
+
city_kana: string; // "ちよだく"
|
|
366
|
+
town: string; // "千代田"
|
|
367
|
+
town_kana: string; // "ちよだ"
|
|
368
|
+
x: string; // "139.7533" (Kinh độ)
|
|
369
|
+
y: string; // "35.6852" (Vĩ độ)
|
|
370
|
+
prefecture: string; // "東京都"
|
|
371
|
+
postal: string; // "1000001"
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
export interface SearchOptions {
|
|
375
|
+
raw?: boolean;
|
|
376
|
+
all?: boolean;
|
|
377
|
+
baseUrl?: string;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export interface SuggestOptions extends SearchOptions {
|
|
381
|
+
matching?: 'prefix' | 'suffix' | 'like';
|
|
382
|
+
}
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
---
|
|
386
|
+
|
|
387
|
+
## 🧪 Kiểm thử (Testing)
|
|
388
|
+
|
|
389
|
+
Thư viện sử dụng Node.js Test Runner tiêu chuẩn (`node:test` và `node:assert/strict`), không cần cài đặt thêm Jest hay Mocha:
|
|
390
|
+
|
|
391
|
+
```bash
|
|
392
|
+
cd /home/dungdao/projects/jp-postal-lookup
|
|
393
|
+
|
|
394
|
+
# Chạy test suite
|
|
395
|
+
npm test
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
### Các kịch bản test bao phủ:
|
|
399
|
+
1. `normalizePostal`: Xử lý dấu gạch ngang half-width, full-width (`-`, `ー`, `-`), khoảng trắng nửa góc & toàn góc, giá trị `null`/`undefined`.
|
|
400
|
+
2. `onSearchAddressByPostcode`: Tìm địa chỉ chính xác theo định dạng chuỗi và object.
|
|
401
|
+
3. Mã bưu điện không tồn tại (`000-0000`) hoặc rỗng: Trả về chuỗi rỗng `''` hoặc `null`, không làm crash ứng dụng.
|
|
402
|
+
4. `onSearchPostcodeByAddress`: Tìm zip code theo keyword & xử lý keyword không khớp.
|
|
403
|
+
5. `getPrefecturesByArea`, `onGetCitiesByPrefecture`, `onGetTownsByCity`: Kiểm thử cả luồng Promise và Callback.
|
|
404
|
+
6. Modern Promise API: Kiểm thử các tuỳ chọn `{ raw: true }`, `{ all: true }`, `{ matching: 'like' }`.
|
|
405
|
+
|
|
406
|
+
---
|
|
407
|
+
|
|
408
|
+
## ⚠️ Xử lý lỗi & Lưu ý (Error Handling & Gotchas)
|
|
409
|
+
|
|
410
|
+
1. **HeartRails Geo API**:
|
|
411
|
+
- Thư viện gửi request tới API công khai miễn phí `https://geoapi.heartrails.com/api/json`.
|
|
412
|
+
- Nếu dự án chạy trên môi trường không có internet hoặc bị chặn CORS từ domain nội bộ, bạn có thể truyền `baseUrl` trỏ tới reverse proxy riêng của công ty:
|
|
413
|
+
```javascript
|
|
414
|
+
searchAddressByPostal('1000001', { baseUrl: '/api/proxy/heartrails' });
|
|
415
|
+
```
|
|
416
|
+
2. **Network Fail-safe**:
|
|
417
|
+
- Mọi hàm bên trong đều có `try/catch` bọc an toàn. Khi mất mạng hoặc API lỗi 500, hàm sẽ trả về `''` (hoặc `null`/`[]` tuỳ theo tuỳ chọn `raw`/`all`), không throw unhandled rejection.
|
|
418
|
+
|
|
419
|
+
---
|
|
420
|
+
|
|
421
|
+
## 🚢 Hướng dẫn Publish lên npm
|
|
422
|
+
|
|
423
|
+
### Bước 1: Đăng ký & Đăng nhập npm
|
|
424
|
+
```bash
|
|
425
|
+
npm login
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
### Bước 2: Kiểm tra package name
|
|
429
|
+
Trong `package.json`:
|
|
430
|
+
- Nếu publish public: `"name": "jp-postal-lookup"`
|
|
431
|
+
- Nếu publish scoped theo user/org: `"name": "@dungdao/jp-postal-lookup"`
|
|
432
|
+
|
|
433
|
+
### Bước 3: Chạy test & kiểm tra files
|
|
434
|
+
```bash
|
|
435
|
+
npm test
|
|
436
|
+
npm pack --dry-run
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
### Bước 4: Publish
|
|
440
|
+
```bash
|
|
441
|
+
# Package thường:
|
|
442
|
+
npm publish
|
|
443
|
+
|
|
444
|
+
# Hoặc Scoped package public:
|
|
445
|
+
npm publish --access public
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
---
|
|
449
|
+
|
|
450
|
+
## 📄 License
|
|
451
|
+
|
|
452
|
+
Phát hành dưới giấy phép [MIT License](LICENSE) © 2026 dungdao.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
export interface GeoLocation {
|
|
2
|
+
city: string;
|
|
3
|
+
city_kana: string;
|
|
4
|
+
town: string;
|
|
5
|
+
town_kana: string;
|
|
6
|
+
x: string;
|
|
7
|
+
y: string;
|
|
8
|
+
prefecture: string;
|
|
9
|
+
postal: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface SearchOptions {
|
|
13
|
+
raw?: boolean;
|
|
14
|
+
all?: boolean;
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface SuggestOptions extends SearchOptions {
|
|
19
|
+
matching?: 'prefix' | 'suffix' | 'like';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export declare const DEFAULT_API_BASE_URL: string;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Remove hyphens and whitespace from postal code.
|
|
26
|
+
*/
|
|
27
|
+
export declare function normalizePostal(postal: string | number): string;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Legacy API: Get prefectures by area with optional callback.
|
|
31
|
+
*/
|
|
32
|
+
export declare function getPrefecturesByArea(
|
|
33
|
+
area: string,
|
|
34
|
+
callback?: (response: { prefecture: string[] } | null) => void,
|
|
35
|
+
baseUrl?: string
|
|
36
|
+
): Promise<{ prefecture: string[] } | null>;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Legacy API: Get cities by area and prefecture with optional callback.
|
|
40
|
+
*/
|
|
41
|
+
export declare function onGetCitiesByPrefecture(
|
|
42
|
+
area: string,
|
|
43
|
+
prefecture: string,
|
|
44
|
+
callback?: (response: { city: string[] } | null) => void,
|
|
45
|
+
baseUrl?: string
|
|
46
|
+
): Promise<{ city: string[] } | null>;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Legacy API: Get towns by city and prefecture with optional callback.
|
|
50
|
+
*/
|
|
51
|
+
export declare function onGetTownsByCity(
|
|
52
|
+
city: string,
|
|
53
|
+
prefecture: string,
|
|
54
|
+
callback?: (response: { town: string[] } | null) => void,
|
|
55
|
+
baseUrl?: string
|
|
56
|
+
): Promise<{ town: string[] } | null>;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Legacy API: Search address by postal code.
|
|
60
|
+
* @param postcode - Postal code with or without hyphen
|
|
61
|
+
* @param isResponse - If true returns raw GeoLocation, otherwise formatted string
|
|
62
|
+
*/
|
|
63
|
+
export declare function onSearchAddressByPostcode(
|
|
64
|
+
postcode: string | number,
|
|
65
|
+
isResponse?: false,
|
|
66
|
+
baseUrl?: string
|
|
67
|
+
): Promise<string>;
|
|
68
|
+
export declare function onSearchAddressByPostcode(
|
|
69
|
+
postcode: string | number,
|
|
70
|
+
isResponse: true,
|
|
71
|
+
baseUrl?: string
|
|
72
|
+
): Promise<GeoLocation | null>;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Legacy API: Search postal code by address string.
|
|
76
|
+
*/
|
|
77
|
+
export declare function onSearchPostcodeByAddress(
|
|
78
|
+
address: string,
|
|
79
|
+
isResponse?: false,
|
|
80
|
+
matching?: 'prefix' | 'suffix' | 'like',
|
|
81
|
+
baseUrl?: string
|
|
82
|
+
): Promise<string>;
|
|
83
|
+
export declare function onSearchPostcodeByAddress(
|
|
84
|
+
address: string,
|
|
85
|
+
isResponse: true,
|
|
86
|
+
matching?: 'prefix' | 'suffix' | 'like',
|
|
87
|
+
baseUrl?: string
|
|
88
|
+
): Promise<GeoLocation | null>;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Modern Promise API: Search address by postal code.
|
|
92
|
+
*/
|
|
93
|
+
export declare function searchAddressByPostal(
|
|
94
|
+
postal: string | number,
|
|
95
|
+
options?: { raw?: false; all?: false; baseUrl?: string }
|
|
96
|
+
): Promise<string>;
|
|
97
|
+
export declare function searchAddressByPostal(
|
|
98
|
+
postal: string | number,
|
|
99
|
+
options: { raw: true; all?: false; baseUrl?: string }
|
|
100
|
+
): Promise<GeoLocation | null>;
|
|
101
|
+
export declare function searchAddressByPostal(
|
|
102
|
+
postal: string | number,
|
|
103
|
+
options: { all: true; raw?: boolean; baseUrl?: string }
|
|
104
|
+
): Promise<GeoLocation[]>;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Modern Promise API: Search postal code by address keyword.
|
|
108
|
+
*/
|
|
109
|
+
export declare function searchPostalByAddress(
|
|
110
|
+
address: string,
|
|
111
|
+
options?: { raw?: false; all?: false; matching?: 'prefix' | 'suffix' | 'like'; baseUrl?: string }
|
|
112
|
+
): Promise<string>;
|
|
113
|
+
export declare function searchPostalByAddress(
|
|
114
|
+
address: string,
|
|
115
|
+
options: { raw: true; all?: false; matching?: 'prefix' | 'suffix' | 'like'; baseUrl?: string }
|
|
116
|
+
): Promise<GeoLocation | null>;
|
|
117
|
+
export declare function searchPostalByAddress(
|
|
118
|
+
address: string,
|
|
119
|
+
options: { all: true; raw?: boolean; matching?: 'prefix' | 'suffix' | 'like'; baseUrl?: string }
|
|
120
|
+
): Promise<GeoLocation[]>;
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Get all areas in Japan.
|
|
124
|
+
*/
|
|
125
|
+
export declare function getAreas(baseUrl?: string): Promise<string[]>;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Get prefectures for a given area.
|
|
129
|
+
*/
|
|
130
|
+
export declare function getPrefectures(area: string, baseUrl?: string): Promise<string[]>;
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Get cities in a prefecture.
|
|
134
|
+
*/
|
|
135
|
+
export declare function getCities(prefecture: string, area?: string, baseUrl?: string): Promise<string[]>;
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Get towns in a city.
|
|
139
|
+
*/
|
|
140
|
+
export declare function getTowns(city: string, prefecture?: string, baseUrl?: string): Promise<string[]>;
|
|
141
|
+
|
|
142
|
+
declare const _default: {
|
|
143
|
+
DEFAULT_API_BASE_URL: string;
|
|
144
|
+
normalizePostal: typeof normalizePostal;
|
|
145
|
+
getPrefecturesByArea: typeof getPrefecturesByArea;
|
|
146
|
+
onGetCitiesByPrefecture: typeof onGetCitiesByPrefecture;
|
|
147
|
+
onGetTownsByCity: typeof onGetTownsByCity;
|
|
148
|
+
onSearchAddressByPostcode: typeof onSearchAddressByPostcode;
|
|
149
|
+
onSearchPostcodeByAddress: typeof onSearchPostcodeByAddress;
|
|
150
|
+
searchAddressByPostal: typeof searchAddressByPostal;
|
|
151
|
+
searchPostalByAddress: typeof searchPostalByAddress;
|
|
152
|
+
getAreas: typeof getAreas;
|
|
153
|
+
getPrefectures: typeof getPrefectures;
|
|
154
|
+
getCities: typeof getCities;
|
|
155
|
+
getTowns: typeof getTowns;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
export default _default;
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jp-postal-lookup",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Zero-dependency Japanese address and postal code lookup library using HeartRails Geo API. Supports ESM, CommonJS, and TypeScript.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"japan",
|
|
7
|
+
"postal",
|
|
8
|
+
"postcode",
|
|
9
|
+
"zipcode",
|
|
10
|
+
"address",
|
|
11
|
+
"heartrails",
|
|
12
|
+
"geo",
|
|
13
|
+
"prefecture",
|
|
14
|
+
"city",
|
|
15
|
+
"town"
|
|
16
|
+
],
|
|
17
|
+
"author": "dungdao",
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"type": "module",
|
|
20
|
+
"main": "./src/index.cjs",
|
|
21
|
+
"module": "./src/index.js",
|
|
22
|
+
"types": "./index.d.ts",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./index.d.ts",
|
|
26
|
+
"import": "./src/index.js",
|
|
27
|
+
"require": "./src/index.cjs"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"src",
|
|
32
|
+
"index.d.ts",
|
|
33
|
+
"README.md",
|
|
34
|
+
"LICENSE"
|
|
35
|
+
],
|
|
36
|
+
"scripts": {
|
|
37
|
+
"test": "node --test tests/index.test.js"
|
|
38
|
+
},
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=18.0.0"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/index.cjs
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
const DEFAULT_API_BASE_URL = 'https://geoapi.heartrails.com/api/json';
|
|
2
|
+
|
|
3
|
+
function normalizePostal(postal) {
|
|
4
|
+
if (postal === null || postal === undefined) return '';
|
|
5
|
+
return String(postal)
|
|
6
|
+
.replace(/[ー--]/g, '')
|
|
7
|
+
.replace(/[\s\u3000]/g, '')
|
|
8
|
+
.trim();
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
async function fetchJson(url, options = {}) {
|
|
12
|
+
const fetchFn = typeof globalThis.fetch === 'function' ? globalThis.fetch : null;
|
|
13
|
+
if (!fetchFn) {
|
|
14
|
+
throw new Error('jp-postal-lookup: Fetch API is not available in this environment.');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
const response = await fetchFn(url, options);
|
|
19
|
+
if (!response.ok) {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
const data = await response.json();
|
|
23
|
+
return data?.response ?? null;
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function getPrefecturesByArea(area, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
30
|
+
const url = `${baseUrl}?method=getPrefectures&area=${encodeURIComponent(area || '')}`;
|
|
31
|
+
const result = await fetchJson(url);
|
|
32
|
+
if (typeof callback === 'function') {
|
|
33
|
+
callback(result);
|
|
34
|
+
}
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function onGetCitiesByPrefecture(area, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
39
|
+
const queryArea = area ? `&area=${encodeURIComponent(area)}` : '';
|
|
40
|
+
const url = `${baseUrl}?method=getCities${queryArea}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
41
|
+
const result = await fetchJson(url);
|
|
42
|
+
if (typeof callback === 'function') {
|
|
43
|
+
callback(result);
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function onGetTownsByCity(city, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
49
|
+
const url = `${baseUrl}?method=getTowns&city=${encodeURIComponent(city || '')}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
50
|
+
const result = await fetchJson(url);
|
|
51
|
+
if (typeof callback === 'function') {
|
|
52
|
+
callback(result);
|
|
53
|
+
}
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function onSearchAddressByPostcode(postcode, isResponse = false, baseUrl = DEFAULT_API_BASE_URL) {
|
|
58
|
+
const cleanCode = normalizePostal(postcode);
|
|
59
|
+
if (!cleanCode) return isResponse ? null : '';
|
|
60
|
+
|
|
61
|
+
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(cleanCode)}`;
|
|
62
|
+
const response = await fetchJson(url);
|
|
63
|
+
|
|
64
|
+
if (!response) {
|
|
65
|
+
return isResponse ? null : '';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const dataAddress = response?.location;
|
|
69
|
+
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
70
|
+
const address = dataAddress[0];
|
|
71
|
+
if (isResponse) {
|
|
72
|
+
return address;
|
|
73
|
+
}
|
|
74
|
+
return `${address.prefecture || ''}${address.city || ''}${address.town || ''}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return isResponse ? null : '';
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function onSearchPostcodeByAddress(
|
|
81
|
+
address,
|
|
82
|
+
isResponse = false,
|
|
83
|
+
matching = 'suffix',
|
|
84
|
+
baseUrl = DEFAULT_API_BASE_URL
|
|
85
|
+
) {
|
|
86
|
+
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
87
|
+
return isResponse ? null : '';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
91
|
+
const response = await fetchJson(url);
|
|
92
|
+
|
|
93
|
+
if (!response) {
|
|
94
|
+
return isResponse ? null : '';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const dataAddress = response?.location;
|
|
98
|
+
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
99
|
+
const item = dataAddress[0];
|
|
100
|
+
return isResponse ? item : item?.postal || '';
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return isResponse ? null : '';
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function searchAddressByPostal(postal, { raw = false, all = false, baseUrl = DEFAULT_API_BASE_URL } = {}) {
|
|
107
|
+
const clean = normalizePostal(postal);
|
|
108
|
+
if (!clean) return all ? [] : raw ? null : '';
|
|
109
|
+
|
|
110
|
+
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(clean)}`;
|
|
111
|
+
const response = await fetchJson(url);
|
|
112
|
+
const locations = response?.location || [];
|
|
113
|
+
|
|
114
|
+
if (!locations.length) {
|
|
115
|
+
return all ? [] : raw ? null : '';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (all) {
|
|
119
|
+
return locations;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const first = locations[0];
|
|
123
|
+
if (raw) {
|
|
124
|
+
return first;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return `${first.prefecture || ''}${first.city || ''}${first.town || ''}`;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function searchPostalByAddress(
|
|
131
|
+
address,
|
|
132
|
+
{ raw = false, all = false, matching = 'suffix', baseUrl = DEFAULT_API_BASE_URL } = {}
|
|
133
|
+
) {
|
|
134
|
+
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
135
|
+
return all ? [] : raw ? null : '';
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
139
|
+
const response = await fetchJson(url);
|
|
140
|
+
const locations = response?.location || [];
|
|
141
|
+
|
|
142
|
+
if (!locations.length) {
|
|
143
|
+
return all ? [] : raw ? null : '';
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (all) {
|
|
147
|
+
return locations;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const first = locations[0];
|
|
151
|
+
return raw ? first : first.postal || '';
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function getAreas(baseUrl = DEFAULT_API_BASE_URL) {
|
|
155
|
+
const url = `${baseUrl}?method=getAreas`;
|
|
156
|
+
const response = await fetchJson(url);
|
|
157
|
+
return response?.area || [];
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function getPrefectures(area, baseUrl = DEFAULT_API_BASE_URL) {
|
|
161
|
+
const response = await getPrefecturesByArea(area, null, baseUrl);
|
|
162
|
+
return response?.prefecture || [];
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function getCities(prefecture, area = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
166
|
+
const response = await onGetCitiesByPrefecture(area, prefecture, null, baseUrl);
|
|
167
|
+
const locations = response?.location || [];
|
|
168
|
+
return locations.map((item) => (typeof item === 'string' ? item : item.city)).filter(Boolean);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function getTowns(city, prefecture = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
172
|
+
const response = await onGetTownsByCity(city, prefecture, null, baseUrl);
|
|
173
|
+
const locations = response?.location || [];
|
|
174
|
+
return locations.map((item) => (typeof item === 'string' ? item : item.town)).filter(Boolean);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
module.exports = {
|
|
178
|
+
DEFAULT_API_BASE_URL,
|
|
179
|
+
normalizePostal,
|
|
180
|
+
getPrefecturesByArea,
|
|
181
|
+
onGetCitiesByPrefecture,
|
|
182
|
+
onGetTownsByCity,
|
|
183
|
+
onSearchAddressByPostcode,
|
|
184
|
+
onSearchPostcodeByAddress,
|
|
185
|
+
searchAddressByPostal,
|
|
186
|
+
searchPostalByAddress,
|
|
187
|
+
getAreas,
|
|
188
|
+
getPrefectures,
|
|
189
|
+
getCities,
|
|
190
|
+
getTowns
|
|
191
|
+
};
|
package/src/index.js
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* jp-postal-lookup
|
|
3
|
+
* Lightweight library to search Japanese addresses, postal codes, prefectures, cities, and towns
|
|
4
|
+
* using HeartRails Geo API with zero runtime dependencies.
|
|
5
|
+
*
|
|
6
|
+
* Compatible with Node.js 18+ and modern browsers.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_API_BASE_URL = 'https://geoapi.heartrails.com/api/json';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Format postal code by removing hyphens and full-width spaces.
|
|
13
|
+
* E.g., "100-0001" -> "1000001"
|
|
14
|
+
* @param {string|number} postal
|
|
15
|
+
* @returns {string}
|
|
16
|
+
*/
|
|
17
|
+
export function normalizePostal(postal) {
|
|
18
|
+
if (postal === null || postal === undefined) return '';
|
|
19
|
+
return String(postal)
|
|
20
|
+
.replace(/[ー--]/g, '')
|
|
21
|
+
.replace(/[\s\u3000]/g, '')
|
|
22
|
+
.trim();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Internal fetch helper with JSON parsing and error handling.
|
|
27
|
+
* @param {string} url
|
|
28
|
+
* @param {RequestInit} [options]
|
|
29
|
+
* @returns {Promise<any>}
|
|
30
|
+
*/
|
|
31
|
+
async function fetchJson(url, options = {}) {
|
|
32
|
+
const fetchFn = typeof globalThis.fetch === 'function' ? globalThis.fetch : null;
|
|
33
|
+
if (!fetchFn) {
|
|
34
|
+
throw new Error('jp-postal-lookup: Fetch API is not available in this environment.');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
const response = await fetchFn(url, options);
|
|
39
|
+
if (!response.ok) {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
const data = await response.json();
|
|
43
|
+
return data?.response ?? null;
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Get list of prefectures by area.
|
|
51
|
+
* @param {string} area - e.g., '関東', '近畿', '中部', etc.
|
|
52
|
+
* @param {Function} [callback] - Optional callback (response) => void
|
|
53
|
+
* @param {string} [baseUrl]
|
|
54
|
+
* @returns {Promise<any>}
|
|
55
|
+
*/
|
|
56
|
+
export async function getPrefecturesByArea(area, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
57
|
+
const url = `${baseUrl}?method=getPrefectures&area=${encodeURIComponent(area || '')}`;
|
|
58
|
+
const result = await fetchJson(url);
|
|
59
|
+
if (typeof callback === 'function') {
|
|
60
|
+
callback(result);
|
|
61
|
+
}
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Get cities by area and prefecture.
|
|
67
|
+
* @param {string} area
|
|
68
|
+
* @param {string} prefecture - e.g., '東京都'
|
|
69
|
+
* @param {Function} [callback]
|
|
70
|
+
* @param {string} [baseUrl]
|
|
71
|
+
* @returns {Promise<any>}
|
|
72
|
+
*/
|
|
73
|
+
export async function onGetCitiesByPrefecture(area, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
74
|
+
const queryArea = area ? `&area=${encodeURIComponent(area)}` : '';
|
|
75
|
+
const url = `${baseUrl}?method=getCities${queryArea}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
76
|
+
const result = await fetchJson(url);
|
|
77
|
+
if (typeof callback === 'function') {
|
|
78
|
+
callback(result);
|
|
79
|
+
}
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Get towns by city and prefecture.
|
|
85
|
+
* @param {string} city - e.g., '千代田区'
|
|
86
|
+
* @param {string} prefecture - e.g., '東京都'
|
|
87
|
+
* @param {Function} [callback]
|
|
88
|
+
* @param {string} [baseUrl]
|
|
89
|
+
* @returns {Promise<any>}
|
|
90
|
+
*/
|
|
91
|
+
export async function onGetTownsByCity(city, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
92
|
+
const url = `${baseUrl}?method=getTowns&city=${encodeURIComponent(city || '')}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
93
|
+
const result = await fetchJson(url);
|
|
94
|
+
if (typeof callback === 'function') {
|
|
95
|
+
callback(result);
|
|
96
|
+
}
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Search address by postal code.
|
|
102
|
+
* @param {string|number} postcode - Japanese postal code (with or without hyphen)
|
|
103
|
+
* @param {boolean} [isResponse=false] - If true, returns the raw location object; otherwise returns formatted address string
|
|
104
|
+
* @param {string} [baseUrl]
|
|
105
|
+
* @returns {Promise<string|object|null>}
|
|
106
|
+
*/
|
|
107
|
+
export async function onSearchAddressByPostcode(postcode, isResponse = false, baseUrl = DEFAULT_API_BASE_URL) {
|
|
108
|
+
const cleanCode = normalizePostal(postcode);
|
|
109
|
+
if (!cleanCode) return isResponse ? null : '';
|
|
110
|
+
|
|
111
|
+
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(cleanCode)}`;
|
|
112
|
+
const response = await fetchJson(url);
|
|
113
|
+
|
|
114
|
+
if (!response) {
|
|
115
|
+
return isResponse ? null : '';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const dataAddress = response?.location;
|
|
119
|
+
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
120
|
+
const address = dataAddress[0];
|
|
121
|
+
if (isResponse) {
|
|
122
|
+
return address;
|
|
123
|
+
}
|
|
124
|
+
return `${address.prefecture || ''}${address.city || ''}${address.town || ''}`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return isResponse ? null : '';
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Search postal code by address string.
|
|
132
|
+
* @param {string} address - Address keyword (e.g. '東京都千代田区')
|
|
133
|
+
* @param {boolean} [isResponse=false] - If true, returns the raw location object; otherwise returns postal string
|
|
134
|
+
* @param {string} [matching='suffix'] - 'prefix', 'suffix', or 'like'
|
|
135
|
+
* @param {string} [baseUrl]
|
|
136
|
+
* @returns {Promise<string|object|null>}
|
|
137
|
+
*/
|
|
138
|
+
export async function onSearchPostcodeByAddress(
|
|
139
|
+
address,
|
|
140
|
+
isResponse = false,
|
|
141
|
+
matching = 'suffix',
|
|
142
|
+
baseUrl = DEFAULT_API_BASE_URL
|
|
143
|
+
) {
|
|
144
|
+
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
145
|
+
return isResponse ? null : '';
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
149
|
+
const response = await fetchJson(url);
|
|
150
|
+
|
|
151
|
+
if (!response) {
|
|
152
|
+
return isResponse ? null : '';
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const dataAddress = response?.location;
|
|
156
|
+
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
157
|
+
const item = dataAddress[0];
|
|
158
|
+
return isResponse ? item : item?.postal || '';
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return isResponse ? null : '';
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// -------------------------------------------------------------
|
|
165
|
+
// Modern Idiomatic Aliases
|
|
166
|
+
// -------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Search full address by postal code.
|
|
170
|
+
* @param {string|number} postal
|
|
171
|
+
* @param {object} [options]
|
|
172
|
+
* @param {boolean} [options.raw=false]
|
|
173
|
+
* @param {boolean} [options.all=false] - Return array of all matched locations
|
|
174
|
+
* @param {string} [options.baseUrl]
|
|
175
|
+
* @returns {Promise<string|object|object[]|null>}
|
|
176
|
+
*/
|
|
177
|
+
export async function searchAddressByPostal(postal, { raw = false, all = false, baseUrl = DEFAULT_API_BASE_URL } = {}) {
|
|
178
|
+
const clean = normalizePostal(postal);
|
|
179
|
+
if (!clean) return all ? [] : raw ? null : '';
|
|
180
|
+
|
|
181
|
+
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(clean)}`;
|
|
182
|
+
const response = await fetchJson(url);
|
|
183
|
+
const locations = response?.location || [];
|
|
184
|
+
|
|
185
|
+
if (!locations.length) {
|
|
186
|
+
return all ? [] : raw ? null : '';
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (all) {
|
|
190
|
+
return locations;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const first = locations[0];
|
|
194
|
+
if (raw) {
|
|
195
|
+
return first;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return `${first.prefecture || ''}${first.city || ''}${first.town || ''}`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Search postal code by address keyword.
|
|
203
|
+
* @param {string} address
|
|
204
|
+
* @param {object} [options]
|
|
205
|
+
* @param {boolean} [options.raw=false]
|
|
206
|
+
* @param {boolean} [options.all=false]
|
|
207
|
+
* @param {'prefix'|'suffix'|'like'} [options.matching='suffix']
|
|
208
|
+
* @param {string} [options.baseUrl]
|
|
209
|
+
* @returns {Promise<string|object|object[]|null>}
|
|
210
|
+
*/
|
|
211
|
+
export async function searchPostalByAddress(
|
|
212
|
+
address,
|
|
213
|
+
{ raw = false, all = false, matching = 'suffix', baseUrl = DEFAULT_API_BASE_URL } = {}
|
|
214
|
+
) {
|
|
215
|
+
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
216
|
+
return all ? [] : raw ? null : '';
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
220
|
+
const response = await fetchJson(url);
|
|
221
|
+
const locations = response?.location || [];
|
|
222
|
+
|
|
223
|
+
if (!locations.length) {
|
|
224
|
+
return all ? [] : raw ? null : '';
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (all) {
|
|
228
|
+
return locations;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const first = locations[0];
|
|
232
|
+
return raw ? first : first.postal || '';
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Get areas in Japan (Hokkaido, Tohoku, Kanto, Chubu, Kinki, Chugoku, Shikoku, Kyushu).
|
|
237
|
+
* @param {string} [baseUrl]
|
|
238
|
+
* @returns {Promise<string[]>}
|
|
239
|
+
*/
|
|
240
|
+
export async function getAreas(baseUrl = DEFAULT_API_BASE_URL) {
|
|
241
|
+
const url = `${baseUrl}?method=getAreas`;
|
|
242
|
+
const response = await fetchJson(url);
|
|
243
|
+
return response?.area || [];
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Get prefectures in an area.
|
|
248
|
+
* @param {string} area
|
|
249
|
+
* @param {string} [baseUrl]
|
|
250
|
+
* @returns {Promise<string[]>}
|
|
251
|
+
*/
|
|
252
|
+
export async function getPrefectures(area, baseUrl = DEFAULT_API_BASE_URL) {
|
|
253
|
+
const response = await getPrefecturesByArea(area, null, baseUrl);
|
|
254
|
+
return response?.prefecture || [];
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Get cities in a prefecture.
|
|
259
|
+
* @param {string} prefecture
|
|
260
|
+
* @param {string} [area]
|
|
261
|
+
* @param {string} [baseUrl]
|
|
262
|
+
* @returns {Promise<string[]>}
|
|
263
|
+
*/
|
|
264
|
+
export async function getCities(prefecture, area = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
265
|
+
const response = await onGetCitiesByPrefecture(area, prefecture, null, baseUrl);
|
|
266
|
+
const locations = response?.location || [];
|
|
267
|
+
return locations.map((item) => (typeof item === 'string' ? item : item.city)).filter(Boolean);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Get towns in a city.
|
|
272
|
+
* @param {string} city
|
|
273
|
+
* @param {string} [prefecture]
|
|
274
|
+
* @param {string} [baseUrl]
|
|
275
|
+
* @returns {Promise<string[]>}
|
|
276
|
+
*/
|
|
277
|
+
export async function getTowns(city, prefecture = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
278
|
+
const response = await onGetTownsByCity(city, prefecture, null, baseUrl);
|
|
279
|
+
const locations = response?.location || [];
|
|
280
|
+
return locations.map((item) => (typeof item === 'string' ? item : item.town)).filter(Boolean);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export default {
|
|
284
|
+
DEFAULT_API_BASE_URL,
|
|
285
|
+
normalizePostal,
|
|
286
|
+
getPrefecturesByArea,
|
|
287
|
+
onGetCitiesByPrefecture,
|
|
288
|
+
onGetTownsByCity,
|
|
289
|
+
onSearchAddressByPostcode,
|
|
290
|
+
onSearchPostcodeByAddress,
|
|
291
|
+
searchAddressByPostal,
|
|
292
|
+
searchPostalByAddress,
|
|
293
|
+
getAreas,
|
|
294
|
+
getPrefectures,
|
|
295
|
+
getCities,
|
|
296
|
+
getTowns
|
|
297
|
+
};
|