69 lines
1.5 KiB
JavaScript
69 lines
1.5 KiB
JavaScript
'use strict';
|
|
|
|
const { Service } = require('egg');
|
|
|
|
const DEFAULT_CACHE_TTL_SECONDS = 600;
|
|
|
|
class ExpressService extends Service {
|
|
getExpressListCacheKey() {
|
|
return 'express:list';
|
|
}
|
|
|
|
normalizeExpressRow(row) {
|
|
if (!row || typeof row !== 'object') {
|
|
return null;
|
|
}
|
|
|
|
const code = String(row.code || '').trim();
|
|
if (!code) {
|
|
return null;
|
|
}
|
|
|
|
return {
|
|
code,
|
|
name: String(row.name || '').trim(),
|
|
value: code,
|
|
label: String(row.name || code).trim(),
|
|
};
|
|
}
|
|
|
|
async loadExpressListFromDatabase() {
|
|
const rows = await this.ctx.model.Express.findAll({
|
|
attributes: [ 'code', 'name' ],
|
|
order: [[ 'code', 'ASC' ]],
|
|
raw: true,
|
|
});
|
|
|
|
if (!Array.isArray(rows)) {
|
|
return [];
|
|
}
|
|
|
|
return rows
|
|
.map(row => this.normalizeExpressRow(row))
|
|
.filter(Boolean);
|
|
}
|
|
|
|
async getExpressList() {
|
|
const cacheKey = this.getExpressListCacheKey();
|
|
|
|
try {
|
|
const cachedList = await this.app.getCacheAsync(cacheKey);
|
|
if (cachedList !== null && cachedList !== undefined) {
|
|
return Array.isArray(cachedList) ? cachedList : [];
|
|
}
|
|
|
|
const expressList = await this.loadExpressListFromDatabase();
|
|
await this.app.setCacheAsync(cacheKey, expressList, DEFAULT_CACHE_TTL_SECONDS);
|
|
|
|
return expressList;
|
|
} catch (error) {
|
|
this.ctx.logger.error('[ExpressService.getExpressList] 获取快递列表失败', {
|
|
error: error.message,
|
|
stack: error.stack,
|
|
});
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = ExpressService; |