油价集成
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
// apizero 接口的文件缓存
|
||||
// - 按 key 存 JSON 到磁盘: <APIZERO_CACHE_DIR>/<key>.json
|
||||
// - 存在性检查: 文件在即视为有效 (用户要求: "同一个年份只要存在就不再调用接口")
|
||||
// - 不做 TTL: 用户没要求, 也避免误命中过期数据
|
||||
//
|
||||
// 环境变量:
|
||||
// APIZERO_CACHE_DIR 缓存目录 (默认 <cwd>/cache/apizero)
|
||||
//
|
||||
// 未来若要加 TTL / DB 后端, 替换本文件即可, 上层调用方不变.
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
function dir() {
|
||||
return process.env.APIZERO_CACHE_DIR
|
||||
? path.resolve(process.env.APIZERO_CACHE_DIR)
|
||||
: path.resolve(process.cwd(), 'cache', 'apizero')
|
||||
}
|
||||
|
||||
// 读缓存, 不存在返回 null
|
||||
export function read(key) {
|
||||
const p = path.join(dir(), key + '.json')
|
||||
if (!fs.existsSync(p)) return null
|
||||
try {
|
||||
const raw = fs.readFileSync(p, 'utf8')
|
||||
return JSON.parse(raw)
|
||||
} catch (e) {
|
||||
console.warn(`[apizero-cache] 读 ${key} 失败, 忽略:`, e.message)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// 写缓存 (原子: 先写 .tmp 再 rename)
|
||||
export function write(key, data) {
|
||||
const d = dir()
|
||||
fs.mkdirSync(d, { recursive: true })
|
||||
const final = path.join(d, key + '.json')
|
||||
const tmp = final + '.tmp.' + process.pid
|
||||
fs.writeFileSync(tmp, JSON.stringify(data), 'utf8')
|
||||
fs.renameSync(tmp, final)
|
||||
return final
|
||||
}
|
||||
|
||||
// 存在性检查
|
||||
export function has(key) {
|
||||
return fs.existsSync(path.join(dir(), key + '.json'))
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// apizero (https://apizero.cn) 通用 HTTP 客户端
|
||||
// - 统一从 env APIZERO_KEY 读取 API key (test key 也能用)
|
||||
// - 统一 QPS 节流 (apizero 限制 3 req/s)
|
||||
// - 统一错误格式: 抛出 ApizeroError(code, message, httpStatus)
|
||||
// - 所有 apizero 接口都进这一层, 后续新增模块复用
|
||||
//
|
||||
// 依赖: 原生 fetch (Node 18+)
|
||||
|
||||
// 简易令牌桶, 限速 3 req/s
|
||||
let lastCallAt = 0
|
||||
const MIN_INTERVAL_MS = 1000 / 3 // ~333ms
|
||||
|
||||
async function throttle() {
|
||||
const now = Date.now()
|
||||
const wait = lastCallAt + MIN_INTERVAL_MS - now
|
||||
if (wait > 0) await new Promise((r) => setTimeout(r, wait))
|
||||
lastCallAt = Date.now()
|
||||
}
|
||||
|
||||
// apizero 标准错误
|
||||
export class ApizeroError extends Error {
|
||||
constructor(code, message, httpStatus) {
|
||||
super(message || `apizero error code=${code}`)
|
||||
this.name = 'ApizeroError'
|
||||
this.code = code
|
||||
this.httpStatus = httpStatus
|
||||
}
|
||||
}
|
||||
|
||||
const BASE_URL = 'https://v1.apizero.cn/api'
|
||||
|
||||
// 读 key: 优先 env APIZERO_KEY, 否则用空 (匿名调用, 配额更小)
|
||||
function getKey() {
|
||||
return process.env.APIZERO_KEY || ''
|
||||
}
|
||||
|
||||
// 通用 GET 入口
|
||||
// - endpoint: 'oil-price-forecast' (不带 /api 前缀)
|
||||
// - params: 普通对象
|
||||
// 返回: apizero 的 data 字段 (已解一层)
|
||||
export async function get(endpoint, params = {}) {
|
||||
await throttle()
|
||||
|
||||
const qs = new URLSearchParams()
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v !== undefined && v !== null && v !== '') qs.set(k, String(v))
|
||||
}
|
||||
const key = getKey()
|
||||
if (key) qs.set('key', key)
|
||||
|
||||
const url = `${BASE_URL}/${endpoint}?${qs.toString()}`
|
||||
let res
|
||||
try {
|
||||
res = await fetch(url, { method: 'GET', headers: { 'Accept': 'application/json' } })
|
||||
} catch (e) {
|
||||
throw new ApizeroError('NETWORK', `apizero 网络错误: ${e.message}`, 0)
|
||||
}
|
||||
|
||||
// HTTP 层错误
|
||||
if (!res.ok) {
|
||||
let body = ''
|
||||
try { body = await res.text() } catch { /* ignore */ }
|
||||
throw new ApizeroError('HTTP', `apizero HTTP ${res.status}: ${body.substring(0, 200)}`, res.status)
|
||||
}
|
||||
|
||||
// 解析 body
|
||||
let json
|
||||
try { json = await res.json() }
|
||||
catch (e) { throw new ApizeroError('PARSE', 'apizero 响应非 JSON: ' + e.message, res.status) }
|
||||
|
||||
// apizero 业务层错误: code !== 0
|
||||
if (json && typeof json.code === 'number' && json.code !== 0) {
|
||||
throw new ApizeroError(json.code, json.msg || 'apizero 业务错误', res.status)
|
||||
}
|
||||
|
||||
return json && json.data !== undefined ? json.data : json
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// apizero 模块统一出口
|
||||
// 后续新增 apizero 接口就在这里再 export 一行
|
||||
export * as oil from './oil-price-forecast.js'
|
||||
export * as history from './oil-history.js'
|
||||
export { ApizeroError } from './client.js'
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// 浙江省油价历史: 走 Prisma 落库 + apizero price 接口写入
|
||||
// 设计:
|
||||
// - 每天 04:00 cron 检查 schedule, 待定且 <= 昨天的调价日 -> 抓 price?province=浙江 存本表
|
||||
// - unique (date, province, fuel) 防重复
|
||||
// - 查询 API: 取某省某油品最近 N 天 (默认 180)
|
||||
import { prisma } from '../db.js'
|
||||
import * as client from './client.js'
|
||||
|
||||
const PROVINCE = '浙江'
|
||||
// 油品 -> apizero prices 对象里的 key (price action 返回 "92号汽油" 这种带后缀的 key)
|
||||
const FUEL_KEYS = {
|
||||
'92': '92号汽油',
|
||||
'95': '95号汽油',
|
||||
'0': '0号柴油',
|
||||
}
|
||||
|
||||
// 解析 apizero price action 返回的 prices (中文 key) -> 标准 fuel code
|
||||
function parsePrice(data) {
|
||||
if (!data || !data.prices) throw new Error('apizero 响应无 prices 字段')
|
||||
const out = {}
|
||||
for (const [fuel, label] of Object.entries(FUEL_KEYS)) {
|
||||
const raw = data.prices[label]
|
||||
if (typeof raw === 'string') {
|
||||
// "7.64 元/升" -> 7.64
|
||||
const m = raw.match(/^([\d.]+)/)
|
||||
if (m) out[fuel] = parseFloat(m[1])
|
||||
} else if (typeof raw === 'number') {
|
||||
out[fuel] = raw
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// 抓一次浙江当前价并入库 (date = 今日)
|
||||
// 返回 { inserted, skipped } (按 unique 约束: 已存在则 skip)
|
||||
export async function fetchAndStore() {
|
||||
const data = await client.get('oil-price-forecast', { action: 'price', province: PROVINCE })
|
||||
const prices = parsePrice(data)
|
||||
if (Object.keys(prices).length === 0) {
|
||||
throw new Error('apizero 返回价格为空')
|
||||
}
|
||||
const date = new Date()
|
||||
// 抹掉时分秒, 便于按天比较
|
||||
date.setHours(0, 0, 0, 0)
|
||||
|
||||
let inserted = 0
|
||||
let skipped = 0
|
||||
for (const [fuel, price] of Object.entries(prices)) {
|
||||
try {
|
||||
await prisma.oilPriceHistory.create({
|
||||
data: { date, province: PROVINCE, fuel, price, source: 'apizero' },
|
||||
})
|
||||
inserted++
|
||||
} catch (e) {
|
||||
// P2002: unique 冲突 -> 跳过
|
||||
if (e?.code === 'P2002') skipped++
|
||||
else throw e
|
||||
}
|
||||
}
|
||||
return { inserted, skipped, date: date.toISOString().slice(0, 10) }
|
||||
}
|
||||
|
||||
// 查询某省某油品最近 N 天
|
||||
// province 必填, 默认 浙江
|
||||
// fuel 可选, 留空返回 4 个油品
|
||||
// days 默认 180
|
||||
export async function query({ province = PROVINCE, fuel, days = 180 }) {
|
||||
const since = new Date()
|
||||
since.setDate(since.getDate() - days)
|
||||
since.setHours(0, 0, 0, 0)
|
||||
|
||||
const where = { province, date: { gte: since } }
|
||||
if (fuel) where.fuel = fuel
|
||||
|
||||
const rows = await prisma.oilPriceHistory.findMany({
|
||||
where,
|
||||
orderBy: [{ date: 'asc' }],
|
||||
})
|
||||
|
||||
// 整形: Decimal -> number
|
||||
return rows.map((r) => ({
|
||||
date: r.date.toISOString().slice(0, 10),
|
||||
province: r.province,
|
||||
fuel: r.fuel,
|
||||
price: Number(r.price),
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// apizero: 今日油价 (oil-price-forecast)
|
||||
// 4 个 action:
|
||||
// forecast - 油价 + 国际原油 + 下次调价预测 (每次都查实时, 不缓存)
|
||||
// price - 单省油价
|
||||
// price-all - 32 省全部油价
|
||||
// schedule - 某年调价日历 (按 year 缓存到文件, 同年份不重复调)
|
||||
//
|
||||
// 文档: https://apizero.cn/aidocs/oil-price-forecast/raw.md
|
||||
import * as client from './client.js'
|
||||
import * as cache from './cache.js'
|
||||
|
||||
// 调价日历: 按年份缓存, 文件存在即视为有效, 不重复调用
|
||||
// cache key 形如 "oil-schedule-2026"
|
||||
export async function getSchedule(year) {
|
||||
const y = Number(year)
|
||||
if (!Number.isInteger(y) || y < 2025 || y > 2026) {
|
||||
throw new client.ApizeroError(4000, `year 不在 2025-2026 范围: ${year}`, 400)
|
||||
}
|
||||
const cacheKey = `oil-schedule-${y}`
|
||||
const hit = cache.read(cacheKey)
|
||||
if (hit) return { ...hit, _cached: true }
|
||||
const data = await client.get('oil-price-forecast', { action: 'schedule', year: y })
|
||||
cache.write(cacheKey, data)
|
||||
return { ...data, _cached: false }
|
||||
}
|
||||
|
||||
// 实时: 国际原油 + 下次调价预测
|
||||
export async function getForecast() {
|
||||
return client.get('oil-price-forecast', { action: 'forecast' })
|
||||
}
|
||||
|
||||
// 单省油价
|
||||
export async function getPrice(province) {
|
||||
if (!province) throw new client.ApizeroError(4000, 'province 必填', 400)
|
||||
return client.get('oil-price-forecast', { action: 'price', province })
|
||||
}
|
||||
|
||||
// 32 省全部油价
|
||||
export async function getPriceAll() {
|
||||
return client.get('oil-price-forecast', { action: 'price-all' })
|
||||
}
|
||||
Reference in New Issue
Block a user