← ToolBox
/ GraphQL 格式化
🌙
◈ GraphQL 格式化
GraphQL 查询语言格式化:美化/压缩,支持 Query/Mutation/Subscription/Fragment/Schema。
美化
压缩
校验
复制
清空
示例
缩进
2 空格
4 空格
Tab
输出结果
等待输入...
已复制
const SAMPLE = 'query GetUser($id: ID!) {\n user(id: $id) {\n id\n name\n email\n posts(first: 10) {\n edges {\n node {\n id\n title\n createdAt\n }\n }\n }\n }\n}'; function tokenize(src){ const tokens = []; let i = 0; const isWs = c => /\s/.test(c); const isName = c => /[A-Za-z_0-9]/.test(c); while(i < src.length){ const c = src[i]; if(isWs(c)){ let s=i; while(i
t.t !== 'ws'); } function formatGraphQL(){ setErr(''); try{ const tokens = tokenize(document.getElementById('input').value); let out = ''; let depth = 0; let atLineStart = true; const pad = () => ' '.repeat(depth); for(const tk of tokens){ if(tk.t === 'comment'){ out += (atLineStart ? pad() : ' ') + tk.v + '\n'; atLineStart = true; continue; } if(tk.v === '{' || tk.v === '[' || tk.v === '('){ out += (atLineStart ? pad() : '') + tk.v + '\n'; depth++; atLineStart = true; continue; } if(tk.v === '}' || tk.v === ']' || tk.v === ')'){ depth = Math.max(0, depth-1); out += pad() + tk.v + '\n'; atLineStart = true; continue; } if(tk.v === ','){ out += tk.v + '\n'; atLineStart = true; continue; } if(atLineStart){ out += pad() + tk.v; atLineStart = false; } else { out += ' ' + tk.v; } } setOut(out.trim()); setErr('✅ 格式化成功'); }catch(e){ setErr('❌ ' + e.message); } } function minifyGraphQL(){ setErr(''); try{ const tokens = tokenize(document.getElementById('input').value); let out = ''; let prev = ''; for(const tk of tokens){ if(tk.t === 'comment') continue; const isName = tk.t === 'name' || tk.t === 'str'; const needSpace = prev && isName && (tk.t === 'name' || tk.t === 'str'); out += (needSpace ? ' ' : '') + tk.v; prev = tk.v; } setOut(out); setErr('✅ 压缩成功'); }catch(e){ setErr('❌ ' + e.message); } } function doBeautify(){ formatGraphQL(); } function doMinify(){ minifyGraphQL(); } function doValidate(){ setErr(''); try{ const tokens = tokenize(document.getElementById('input').value); let depth = 0; for(const tk of tokens){ if(tk.v === '{' || tk.v === '[' || tk.v === '(') depth++; if(tk.v === '}' || tk.v === ']' || tk.v === ')') depth--; if(depth < 0) throw new Error('括号不匹配'); } if(depth !== 0) throw new Error('括号未闭合'); setOut('✅ GraphQL 语法正确\nTokens: ' + tokens.length + '\n括号平衡'); setErr('✅ 校验通过'); }catch(e){ setErr('❌ ' + e.message); } } function getIndent(){const v=document.getElementById('indent').value;return v==='tab'?'\t':' '.repeat(parseInt(v));} function setOut(s){document.getElementById('output').textContent=s;} function setErr(s){const e=document.getElementById('err');e.textContent=s||'';e.className='err'+(s?'':' ok');} function clearAll(){document.getElementById('input').value='';setOut('等待输入...');setErr('');} function loadSample(){document.getElementById('input').value=SAMPLE;doBeautify();}