Last active
July 3, 2022 23:01
-
-
Save exceedsystem/bbc80e15a943456cdc40b065d53d557f to your computer and use it in GitHub Desktop.
VS Code Macros extension macro that generates json schema from typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [VSCode Macros] extension | |
// https://marketplace.visualstudio.com/items?itemName=EXCEEDSYSTEM.vscode-macros | |
// License:MIT | |
const vscode = require('vscode'); | |
const tsjsg = require('ts-json-schema-generator'); | |
const tmpp = require('tmp-promise'); | |
module.exports.macroCommands = { | |
TS2JsonSchema: { | |
no: 1, | |
func: ts2JsonSchemaFunc, | |
}, | |
}; | |
async function ts2JsonSchemaFunc() { | |
const editor = vscode.window.activeTextEditor; | |
if (!editor) { | |
return 'Editor is not open.'; | |
} | |
const document = editor.document; | |
const selection = editor.selection; | |
const text = document.getText(selection); | |
if (text.length === 0) { | |
return 'Nothing is selected.'; | |
} | |
let tmpFile = null; | |
try { | |
tmpFile = await tmpp.file({ postfix: '.ts' }); | |
const textBuf = new TextEncoder().encode(text); | |
await vscode.workspace.fs.writeFile(vscode.Uri.file(tmpFile.path), textBuf); | |
const config = { | |
path: tmpFile.path, | |
//expose: "all", | |
type: '*', | |
}; | |
const jsonSchema = tsjsg.createGenerator(config).createSchema(config.type); | |
const jsonText = JSON.stringify(jsonSchema, null, 2); | |
const jsonDoc = await vscode.workspace.openTextDocument({ | |
language: 'json', | |
content: jsonText | |
}); | |
await vscode.window.showTextDocument(jsonDoc); | |
} | |
catch (e) { | |
return e.message; | |
} | |
finally { | |
tmpFile?.cleanup(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment