Created
May 23, 2024 18:24
-
-
Save JosXa/449326af6c4f1bcb5b599e8767f00eab to your computer and use it in GitHub Desktop.
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
// Name: JSON to TypeScript | |
// Description: Convert some JSON to TypeScript models | |
import "@johnlindquist/kit" | |
import jsonToTS from "json-to-ts" | |
import { submitShortcut } from "@johnlindquist/kit/core/utils" | |
import { refreshable } from "@josxa/kit-utils" | |
import { crudArg } from "@josxa/kit-utils" | |
import ModernError from "modern-errors" | |
import { copyToClipboardShortcut } from "../lib/ui/shortcuts" | |
let json = args[0] | |
if (!json) { | |
json = await editor({ | |
language: "json", | |
validate(input: string): true | string { | |
try { | |
JSON.parse(input) | |
return true | |
} catch (err) { | |
return ModernError.normalize(err).message | |
} | |
}, | |
shortcuts: [submitShortcut], | |
}) | |
} | |
const rootName = await crudArg("Name of the root type?") | |
const options: Parameters<typeof jsonToTS>[1] = { | |
rootName, | |
useTypeAlias: true, | |
} | |
await refreshable(async (refresh) => { | |
let types = "" | |
try { | |
types = `${jsonToTS(JSON.parse(json), options).join("\n\n")}\n` | |
} catch (error) { | |
const hint = ModernError.normalize(error).message | |
setHint(hint) | |
exit() | |
} | |
if (options.useTypeAlias) { | |
types = types.replaceAll(/^type /g, "export type ") | |
} else { | |
types = types.replaceAll(/^interface /g, "export interface ") | |
} | |
await editor({ | |
value: types, | |
language: "ts", | |
shortcuts: [ | |
{ | |
key: `${cmd}+shift+t`, | |
name: `Use ${options.useTypeAlias ? "Interfaces" : "Types"}`, | |
onPress: () => { | |
options.useTypeAlias = !options.useTypeAlias | |
refresh() | |
}, | |
visible: true, | |
bar: "right", | |
}, | |
copyToClipboardShortcut(), | |
], | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment