-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
350 lines (305 loc) · 13.3 KB
/
script.js
File metadata and controls
350 lines (305 loc) · 13.3 KB
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Mock API Generator - 核心逻辑
// 开发者: wangweihanNB
let fieldIdCounter = 1;
let currentJsonBinId = null;
// ========== 初始化默认字段 ==========
function initDefaultField() {
const container = document.getElementById('fieldsContainer');
container.innerHTML = '';
fieldIdCounter = 0;
addField();
// 修改默认字段
const firstField = document.querySelector('.field-card');
if (firstField) {
const nameInput = firstField.querySelector('.field-name');
if (nameInput) nameInput.value = 'name';
const typeSelect = firstField.querySelector('.field-type');
if (typeSelect) typeSelect.value = 'string';
}
addField();
const secondField = document.querySelectorAll('.field-card')[1];
if (secondField) {
const nameInput = secondField.querySelector('.field-name');
if (nameInput) nameInput.value = 'age';
const typeSelect = secondField.querySelector('.field-type');
if (typeSelect) typeSelect.value = 'number';
const minVal = secondField.querySelector('.min-val');
const maxVal = secondField.querySelector('.max-val');
if (minVal) minVal.value = 18;
if (maxVal) maxVal.value = 60;
}
addField();
const thirdField = document.querySelectorAll('.field-card')[2];
if (thirdField) {
const nameInput = thirdField.querySelector('.field-name');
if (nameInput) nameInput.value = 'email';
const typeSelect = thirdField.querySelector('.field-type');
if (typeSelect) typeSelect.value = 'email';
}
}
// ========== 添加字段 ==========
function addField() {
const container = document.getElementById('fieldsContainer');
const fieldId = fieldIdCounter++;
const fieldCard = document.createElement('div');
fieldCard.className = 'field-card';
fieldCard.setAttribute('data-field-id', fieldId);
fieldCard.innerHTML = `
<div class="field-header">
<input type="text" class="field-name" placeholder="字段名 (如: name)" value="field_${fieldId}">
<select class="field-type">
<option value="number">数字 (number)</option>
<option value="string" selected>字符串 (string)</option>
<option value="boolean">布尔值 (boolean)</option>
<option value="array">数组 (array)</option>
<option value="object">对象 (object)</option>
<option value="email">邮箱 (email)</option>
<option value="phone">手机号 (phone)</option>
<option value="url">网址 (url)</option>
<option value="date">日期 (date)</option>
</select>
<button class="btn-remove" onclick="removeField(this)">🗑️</button>
</div>
<div class="field-options">
<div class="option-group number-options" style="display:none;">
<label>最小值: <input type="number" class="min-val" value="1"></label>
<label>最大值: <input type="number" class="max-val" value="100"></label>
</div>
<div class="option-group string-options" style="display:none;">
<label>前缀: <input type="text" class="str-prefix" placeholder="如: user_"></label>
<label>后缀: <input type="text" class="str-suffix" placeholder="如: _001"></label>
</div>
<div class="option-group array-options" style="display:none;">
<label>数组长度: <input type="number" class="array-length" value="3" min="1" max="20"></label>
<label>子元素类型:
<select class="array-item-type">
<option value="number">数字</option>
<option value="string" selected>字符串</option>
<option value="boolean">布尔值</option>
</select>
</label>
</div>
</div>
`;
container.appendChild(fieldCard);
// 绑定类型切换事件
const typeSelect = fieldCard.querySelector('.field-type');
typeSelect.addEventListener('change', () => updateFieldOptionsVisibility(fieldCard));
updateFieldOptionsVisibility(fieldCard);
}
// ========== 删除字段 ==========
function removeField(btn) {
const fieldCard = btn.closest('.field-card');
if (document.querySelectorAll('.field-card').length > 1) {
fieldCard.remove();
} else {
alert('至少保留一个字段');
}
}
// ========== 更新字段选项显示 ==========
function updateFieldOptionsVisibility(fieldCard) {
const type = fieldCard.querySelector('.field-type').value;
const numberOpts = fieldCard.querySelector('.number-options');
const stringOpts = fieldCard.querySelector('.string-options');
const arrayOpts = fieldCard.querySelector('.array-options');
numberOpts.style.display = 'none';
stringOpts.style.display = 'none';
arrayOpts.style.display = 'none';
if (type === 'number') {
numberOpts.style.display = 'flex';
} else if (type === 'string') {
stringOpts.style.display = 'flex';
} else if (type === 'array') {
arrayOpts.style.display = 'flex';
}
}
// ========== 生成随机数据 ==========
function generateRandomValue(type, options = {}) {
switch(type) {
case 'number':
const min = options.min || 1;
const max = options.max || 100;
return Math.floor(Math.random() * (max - min + 1)) + min;
case 'string':
const prefix = options.prefix || '';
const suffix = options.suffix || '';
const randomStr = Math.random().toString(36).substring(2, 8);
return prefix + randomStr + suffix;
case 'boolean':
return Math.random() > 0.5;
case 'array':
const length = options.length || 3;
const itemType = options.itemType || 'string';
const arr = [];
for (let i = 0; i < length; i++) {
arr.push(generateRandomValue(itemType));
}
return arr;
case 'email':
const domains = ['gmail.com', '163.com', 'qq.com', 'outlook.com', 'example.com'];
const username = Math.random().toString(36).substring(2, 10);
const domain = domains[Math.floor(Math.random() * domains.length)];
return `${username}@${domain}`;
case 'phone':
const prefixs = ['130', '131', '132', '155', '156', '185', '186', '188', '189'];
const phonePrefix = prefixs[Math.floor(Math.random() * prefixs.length)];
const rest = Math.floor(Math.random() * 100000000).toString().padStart(8, '0');
return phonePrefix + rest;
case 'url':
const protocols = ['https', 'http'];
const protocol = protocols[Math.floor(Math.random() * protocols.length)];
const names = ['example', 'test', 'api', 'data', 'mock'];
const name = names[Math.floor(Math.random() * names.length)];
const tlds = ['com', 'cn', 'net', 'org'];
const tld = tlds[Math.floor(Math.random() * tlds.length)];
return `${protocol}://${name}.${tld}/api/${Math.random().toString(36).substring(2, 6)}`;
case 'date':
const start = new Date(2020, 0, 1);
const end = new Date();
const randomDate = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
return randomDate.toISOString().split('T')[0];
case 'object':
return { example: 'nested', value: Math.random() > 0.5 ? 'yes' : 'no' };
default:
return 'default value';
}
}
// ========== 获取所有字段配置 ==========
function getFieldConfigs() {
const fields = [];
const fieldCards = document.querySelectorAll('.field-card');
fieldCards.forEach(card => {
const name = card.querySelector('.field-name').value;
const type = card.querySelector('.field-type').value;
const config = { name, type, options: {} };
if (type === 'number') {
config.options.min = parseInt(card.querySelector('.min-val').value) || 0;
config.options.max = parseInt(card.querySelector('.max-val').value) || 100;
} else if (type === 'string') {
config.options.prefix = card.querySelector('.str-prefix').value || '';
config.options.suffix = card.querySelector('.str-suffix').value || '';
} else if (type === 'array') {
config.options.length = parseInt(card.querySelector('.array-length').value) || 3;
config.options.itemType = card.querySelector('.array-item-type').value;
}
fields.push(config);
});
return fields;
}
// ========== 生成单条数据 ==========
function generateSingleData(fields) {
const data = {};
fields.forEach(field => {
if (field.name.trim()) {
data[field.name.trim()] = generateRandomValue(field.type, field.options);
}
});
return data;
}
// ========== 生成全部数据 ==========
function generateData() {
const fields = getFieldConfigs();
const count = parseInt(document.getElementById('dataCount').value) || 5;
const result = [];
for (let i = 0; i < count; i++) {
result.push(generateSingleData(fields));
}
return result;
}
// ========== 显示 JSON 输出 ==========
function displayJson(data) {
const pretty = document.getElementById('prettyJson').checked;
const output = document.getElementById('outputJson');
if (pretty) {
output.textContent = JSON.stringify(data, null, 2);
} else {
output.textContent = JSON.stringify(data);
}
}
// ========== 生成并显示 ==========
function generateAndDisplay() {
const data = generateData();
displayJson(data);
return data;
}
// ========== 复制到剪贴板 ==========
async function copyToClipboard() {
const jsonContent = document.getElementById('outputJson').textContent;
try {
await navigator.clipboard.writeText(jsonContent);
alert('✅ JSON 已复制到剪贴板');
} catch (err) {
alert('❌ 复制失败,请手动复制');
}
}
// ========== 保存到 JSONBin.io ==========
async function saveToJsonBin() {
const data = generateData();
const apiKey = '$2a$10$8cYqFcKxYqFcKxYqFcKxe'; // 演示用的 key,建议用户自己注册
try {
// 显示加载状态
const saveBtn = document.getElementById('saveToJsonBinBtn');
const originalText = saveBtn.textContent;
saveBtn.textContent = '⏳ 保存中...';
saveBtn.disabled = true;
const response = await fetch('https://api.jsonbin.io/v3/b', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Master-Key': apiKey
},
body: JSON.stringify(data)
});
const result = await response.json();
if (result.metadata && result.metadata.id) {
currentJsonBinId = result.metadata.id;
const apiUrl = `https://api.jsonbin.io/v3/b/${currentJsonBinId}/latest`;
document.getElementById('apiUrl').value = apiUrl;
alert(`✅ 保存成功!\nAPI 地址已生成`);
} else {
// 如果 API key 无效,提供模拟保存
mockSaveToJsonBin(data);
}
} catch (error) {
console.error('保存失败:', error);
mockSaveToJsonBin(data);
} finally {
const saveBtn = document.getElementById('saveToJsonBinBtn');
saveBtn.textContent = '☁️ 保存到 JSONBin.io';
saveBtn.disabled = false;
}
}
// ========== 模拟保存(当 API key 无效时) ==========
function mockSaveToJsonBin(data) {
const mockId = 'mock_' + Date.now();
currentJsonBinId = mockId;
// 将数据保存到 localStorage 模拟
localStorage.setItem('mock_json_bin_' + mockId, JSON.stringify(data));
const apiUrl = `https://wangweihanNB.github.io/mock-api-generator/?id=${mockId}`;
document.getElementById('apiUrl').value = apiUrl;
alert('💡 提示:使用模拟保存模式\n数据已保存到本地,如需真实 API 请注册 JSONBin.io 账号');
}
// ========== 复制 API 地址 ==========
async function copyApiUrl() {
const apiUrlInput = document.getElementById('apiUrl');
if (apiUrlInput.value) {
await navigator.clipboard.writeText(apiUrlInput.value);
alert('✅ API 地址已复制');
} else {
alert('❌ 请先保存数据生成 API 地址');
}
}
// ========== 事件绑定 ==========
document.addEventListener('DOMContentLoaded', () => {
initDefaultField();
document.getElementById('generateBtn').addEventListener('click', generateAndDisplay);
document.getElementById('copyBtn').addEventListener('click', copyToClipboard);
document.getElementById('saveToJsonBinBtn').addEventListener('click', saveToJsonBin);
document.getElementById('copyApiBtn').addEventListener('click', copyApiUrl);
// 添加字段按钮
document.getElementById('addFieldBtn').addEventListener('click', addField);
// 初始生成一次示例数据
setTimeout(() => {
generateAndDisplay();
}, 100);
});