1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
|
// 公園・公共施設データの簡易エディタ(ローカル専用)。
//
// 使い方:
// npm run park-editor
// → 表示された URL(既定 http://localhost:8787/)をブラウザで開く
// → タブで「市内公園 / 周辺の公園 / 市内の公共施設 / 周辺の公共施設」を切り替え
// → 表のセルを直接編集し、「保存」を押すと該当するJSONを更新
// → 反映確認後、git にコミットする
//
// 注意: ローカル(127.0.0.1)にのみ公開します。追加パッケージは不要です。
import { createServer } from "node:http";
import { readFile, writeFile, rename } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const HTML = join(root, "scripts/park-editor.html");
const PORT = Number(process.env.PORT || 8787);
const DATASETS = {
parks: {
label: "市内公園",
path: join(root, "src/data/kodaira-parks.json"),
pretty: false,
},
nearbyParks: {
label: "周辺の公園",
path: join(root, "src/data/kodaira-nearby-parks.json"),
pretty: false,
},
facilities: {
label: "市内の公共施設",
path: join(root, "src/data/kodaira-facilities.json"),
pretty: true,
},
nearbyFacilities: {
label: "周辺の公共施設",
path: join(root, "src/data/kodaira-nearby-facilities.json"),
pretty: true,
},
};
function send(res, code, type, body) {
res.writeHead(code, { "content-type": type });
res.end(body);
}
function datasetFromUrl(url) {
const match = /^\/api\/data\/([A-Za-z]+)$/.exec(url);
if (!match) return null;
return DATASETS[match[1]] ? { id: match[1], dataset: DATASETS[match[1]] } : null;
}
// 文字化け(U+FFFD)の場所を「レコード名 / 項目名」で返す。
// 保存は止めず、どこを直せばよいか分かるようにするための情報。
const NAME_KEYS = ["公園名", "name", "名称", "our_name"];
function recordLabel(obj) {
const sources = [];
if (obj && obj.properties) sources.push(obj.properties);
sources.push(obj);
for (const source of sources) {
for (const key of NAME_KEYS) {
const value = source && source[key];
if (typeof value === "string" && value) return value;
}
}
return "";
}
function findCorruptions(value, path, out) {
if (typeof value === "string") {
if (value.includes("\uFFFD")) out.push({ where: path, value });
} else if (Array.isArray(value)) {
value.forEach((item, index) => {
const label = recordLabel(item);
findCorruptions(item, label || `${path}[${index + 1}]`, out);
});
} else if (value && typeof value === "object") {
for (const [key, child] of Object.entries(value)) {
if (key.includes("\uFFFD")) out.push({ where: `${path} / ${key}(項目名)`, value: "" });
findCorruptions(child, path ? `${path} / ${key}` : key, out);
}
}
return out;
}
function recordKey(obj) {
const src = obj && obj.properties ? obj.properties : obj;
if (!src) return null;
for (const key of ["公園名", "name", "名称", "our_name"]) {
const value = src[key];
if (typeof value === "string" && value) return value;
}
return null;
}
// ブラウザが古いデータを持っていても、後から足した項目やレコードを消さないようにする。
// 画面になくて編集できないキーは、ディスク側の値を残す。
function mergeMissing(postedList, currentList) {
const map = new Map();
for (const rec of currentList) {
const key = recordKey(rec);
if (key) map.set(key, rec);
}
const postedKeys = new Set();
for (const rec of postedList) {
const key = recordKey(rec);
if (!key) continue;
postedKeys.add(key);
const current = map.get(key);
if (!current) continue;
const dst = rec.properties || rec;
const src = current.properties || current;
for (const [field, value] of Object.entries(src)) {
if (!(field in dst)) dst[field] = value;
}
}
for (const [key, rec] of map) {
if (!postedKeys.has(key)) postedList.push(rec);
}
}
const server = createServer(async (req, res) => {
try {
const url = (req.url || "").split("?")[0];
if (req.method === "GET" && (url === "/" || url === "/index.html")) {
send(res, 200, "text/html; charset=utf-8", await readFile(HTML, "utf-8"));
return;
}
if (req.method === "GET" && url === "/api/datasets") {
send(
res,
200,
"application/json; charset=utf-8",
JSON.stringify(
Object.entries(DATASETS).map(([id, dataset]) => ({ id, label: dataset.label })),
),
);
return;
}
const target = datasetFromUrl(url);
if (!target) {
send(res, 404, "text/plain; charset=utf-8", "not found");
return;
}
if (req.method === "GET") {
send(
res,
200,
"application/json; charset=utf-8",
await readFile(target.dataset.path, "utf-8"),
);
return;
}
if (req.method === "POST") {
let body = "";
for await (const chunk of req) body += chunk;
const data = JSON.parse(body);
if (target.id === "nearbyParks") {
if (!data || data.type !== "FeatureCollection" || !Array.isArray(data.features)) {
throw new Error("周辺の公園は FeatureCollection ではありません");
}
} else if (!Array.isArray(data) || data.length === 0) {
throw new Error("データが配列ではありません");
}
// 古い画面からの保存で、新しい項目・レコードが消えないようにマージする
const current = JSON.parse(await readFile(target.dataset.path, "utf-8"));
if (target.id === "nearbyParks") {
mergeMissing(data.features, current.features || []);
} else {
mergeMissing(data, current);
}
const text = target.dataset.pretty
? `${JSON.stringify(data, null, 2)}\n`
: `${JSON.stringify(data)}\n`;
if (text.includes("\uFFFD")) {
// 保存は中止せず、どこが文字化けしているかを返す(入力内容を失わないため)
console.warn("文字化け(U+FFFD)を含むデータを保存しました");
}
const warnings = findCorruptions(data, "", []).slice(0, 50);
if (warnings.length) {
for (const warning of warnings.slice(0, 10)) {
console.warn(` 文字化け: ${warning.where} = ${warning.value}`);
}
}
const tmp = `${target.dataset.path}.tmp`;
await writeFile(tmp, text, "utf-8");
await rename(tmp, target.dataset.path);
const count = target.id === "nearbyParks" ? data.features.length : data.length;
console.log(`保存しました: ${target.dataset.label} ${count}件 → ${target.dataset.path}`);
send(
res,
200,
"application/json; charset=utf-8",
JSON.stringify({ ok: true, count, warnings }),
);
return;
}
send(res, 405, "text/plain; charset=utf-8", "method not allowed");
} catch (e) {
console.error(e);
send(res, 500, "text/plain; charset=utf-8", String(e));
}
});
server.listen(PORT, "127.0.0.1", () => {
console.log(`公園・施設データ編集: http://localhost:${PORT}/ (Ctrl+C で終了)`);
});
|