Created
February 26, 2024 22:11
-
-
Save cdcarson/068e65e1ca43252bd59d363689addb45 to your computer and use it in GitHub Desktop.
helper script to generate sveltekit url functions
This file contains hidden or 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
import { readFile, writeFile, stat, mkdir } from 'node:fs/promises'; | |
import { join } from 'node:path'; | |
import { format } from 'prettier'; | |
const fileText = await readFile( | |
'.svelte-kit/types/route_meta_data.json', | |
'utf-8' | |
); | |
const routes = JSON.parse(fileText); | |
const routeIds = Object.keys(routes).sort(); | |
const paramRx = /\[{1,2}([^\]]+)\]{1,2}/g; | |
const funcDecls = routeIds.map((id) => { | |
const params = Array.from(id.matchAll(paramRx)).map((s) => | |
{ | |
return { | |
param: s[1].replace(/^\.+/, ''), | |
optional: s[0].indexOf('[[') === 0 | |
} | |
} | |
); | |
const allParamsOptional = params.find(p => !p.optional) === undefined; | |
const paramsDecl = | |
params.length === 0 | |
? '' | |
: ` | |
params: {${params.map((p) => `${p.param}${p.optional ? '?' : ''}: string;`).join('')}} ${allParamsOptional ? '={}' : ''} | |
`.trim(); | |
return `'${id}': (${paramsDecl}): string => resolveRoute('${id}', ${paramsDecl.length > 0 ? 'params' : '{}'})`; | |
}); | |
const ts = ` | |
import {resolveRoute} from '$app/paths'; | |
export const appUrls = {${funcDecls.join(',')}} | |
`; | |
const folderPath = join('src', 'lib', 'app-urls'); | |
const filePath = join(folderPath, 'app-urls-generated.ts'); | |
const prettified = await format(ts, { | |
singleQuote: true, | |
trailingComma: 'none', | |
filepath: filePath | |
}); | |
try { | |
await stat(folderPath); | |
} catch (error) { | |
mkdir(folderPath); | |
} | |
await writeFile(filePath, prettified); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment