You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
2.4 KiB
96 lines
2.4 KiB
const fs = require('fs-extra');
|
|
const path = require('path');
|
|
|
|
const CONFIG_DIR = path.join(process.cwd(), 'data');
|
|
const CONFIG_PATH = path.join(CONFIG_DIR, 'location-config.json');
|
|
|
|
const DEFAULT_LOCATION = {
|
|
longitude: 0,
|
|
latitude: 0,
|
|
};
|
|
|
|
const readRawBody = (req) =>
|
|
new Promise((resolve, reject) => {
|
|
let raw = '';
|
|
req.setEncoding('utf8');
|
|
req.on('data', (chunk) => {
|
|
raw += chunk;
|
|
});
|
|
req.on('end', () => resolve(raw));
|
|
req.on('error', reject);
|
|
});
|
|
|
|
const parseRequestBody = async (ctx) => {
|
|
if (ctx.request?.body && Object.keys(ctx.request.body).length > 0) {
|
|
return ctx.request.body;
|
|
}
|
|
|
|
const raw = await readRawBody(ctx.req);
|
|
if (!raw) {
|
|
return {};
|
|
}
|
|
|
|
try {
|
|
return JSON.parse(raw);
|
|
} catch (error) {
|
|
console.error('解析经纬度配置请求体失败:', error);
|
|
return {};
|
|
}
|
|
};
|
|
|
|
const normalizeNumber = (value) => {
|
|
const num = Number(value);
|
|
return Number.isFinite(num) ? num : 0;
|
|
};
|
|
|
|
const ensureConfigDir = async () => {
|
|
await fs.ensureDir(CONFIG_DIR);
|
|
};
|
|
|
|
const readLocationConfig = async () => {
|
|
try {
|
|
await ensureConfigDir();
|
|
const exists = await fs.pathExists(CONFIG_PATH);
|
|
if (!exists) {
|
|
return DEFAULT_LOCATION;
|
|
}
|
|
|
|
const content = await fs.readJson(CONFIG_PATH);
|
|
return {
|
|
longitude: normalizeNumber(content?.longitude),
|
|
latitude: normalizeNumber(content?.latitude),
|
|
};
|
|
} catch (error) {
|
|
console.error('读取经纬度配置失败:', error);
|
|
return DEFAULT_LOCATION;
|
|
}
|
|
};
|
|
|
|
module.exports.getLocationConfig = async (ctx) => {
|
|
ctx.status = 200;
|
|
ctx.body = await readLocationConfig();
|
|
};
|
|
|
|
module.exports.saveLocationConfig = async (ctx) => {
|
|
try {
|
|
const requestBody = await parseRequestBody(ctx);
|
|
const longitude = normalizeNumber(requestBody?.longitude);
|
|
const latitude = normalizeNumber(requestBody?.latitude);
|
|
|
|
await ensureConfigDir();
|
|
const data = { longitude, latitude };
|
|
await fs.writeJson(CONFIG_PATH, data, { spaces: 2 });
|
|
ctx.status = 200;
|
|
ctx.body = {
|
|
success: true,
|
|
...data,
|
|
};
|
|
} catch (error) {
|
|
console.error('保存经纬度配置失败:', error);
|
|
ctx.status = 500;
|
|
ctx.body = {
|
|
success: false,
|
|
message: 'save location config failed',
|
|
};
|
|
}
|
|
};
|
|
|