|
1 | | -const { loadData, setData } = require('./data-loader'); |
| 1 | +import { loadData, setData as _setData } from './data-loader.js'; |
2 | 2 |
|
3 | 3 | /** |
4 | 4 | * 根据 adcode 精确查找 |
5 | 5 | * @param {string} code 行政区划代码 |
6 | 6 | * @returns {Promise<Object|null>} |
7 | 7 | */ |
8 | | -async function get(code) { |
| 8 | +export async function get(code) { |
9 | 9 | const list = await loadData(); |
10 | 10 | if (!list) return null; |
11 | 11 | return list.find(item => item.code === String(code)) || null; |
12 | 12 | } |
13 | 13 |
|
14 | 14 | /** |
15 | | - * 模糊搜索 |
16 | | - * @param {string} keyword 省/市/区/拼音 关键词 |
| 15 | + * 组合条件搜索 |
| 16 | + * @param {string} name 必需,区县名称或关键词 |
| 17 | + * @param {string} [city] 可选,城市名称(包含即可) |
| 18 | + * @param {string} [province] 可选,省份名称(包含即可) |
17 | 19 | * @returns {Promise<Array>} |
18 | 20 | */ |
19 | | -async function search(keyword) { |
20 | | - if (!keyword) return []; |
| 21 | +export async function search(name, city, province) { |
| 22 | + if (!name) return []; |
21 | 23 | const list = await loadData(); |
22 | 24 | if (!list) return []; |
23 | 25 |
|
24 | | - const key = String(keyword).toLowerCase(); |
25 | | - return list.filter(item => |
26 | | - (item.name && item.name.includes(key)) || |
27 | | - (item.province && item.province.includes(key)) || |
28 | | - (item.city && item.city.includes(key)) || |
29 | | - (item.pinyin && item.pinyin.includes(key)) || |
30 | | - (item.zipCode && item.zipCode.includes(key)) |
31 | | - ); |
| 26 | + const keyName = String(name).toLowerCase(); |
| 27 | + const keyCity = city ? String(city).toLowerCase() : null; |
| 28 | + const keyProvince = province ? String(province).toLowerCase() : null; |
| 29 | + |
| 30 | + return list.filter(item => { |
| 31 | + // 1. name 必须包含 |
| 32 | + const matchName = (item.name && item.name.includes(keyName)) || |
| 33 | + (item.pinyin && item.pinyin.includes(keyName)); |
| 34 | + |
| 35 | + if (!matchName) return false; |
| 36 | + |
| 37 | + // 2. 如果传了 city,city 必须包含 |
| 38 | + if (keyCity && (!item.city || !item.city.includes(keyCity))) { |
| 39 | + return false; |
| 40 | + } |
| 41 | + |
| 42 | + // 3. 如果传了 province,province 必须包含 |
| 43 | + if (keyProvince && (!item.province || !item.province.includes(keyProvince))) { |
| 44 | + return false; |
| 45 | + } |
| 46 | + |
| 47 | + return true; |
| 48 | + }); |
32 | 49 | } |
33 | 50 |
|
34 | 51 | /** |
35 | 52 | * 获取所有数据 |
36 | 53 | * @returns {Promise<Array>} |
37 | 54 | */ |
38 | | -async function getAll() { |
| 55 | +export async function getAll() { |
39 | 56 | return await loadData(); |
40 | 57 | } |
41 | 58 |
|
42 | | -module.exports = { |
43 | | - get, |
44 | | - search, |
45 | | - getAll, |
46 | | - setData // 暴露给需要手动注入数据的场景 |
47 | | -}; |
| 59 | +export const setData = _setData; |
0 commit comments