Skip to content

Instantly share code, notes, and snippets.

@jsmnbom
Created July 15, 2025 10:03
Show Gist options
  • Select an option

  • Save jsmnbom/1acfe959b8b6c6217f0952d4b44e5ff1 to your computer and use it in GitHub Desktop.

Select an option

Save jsmnbom/1acfe959b8b6c6217f0952d4b44e5ff1 to your computer and use it in GitHub Desktop.
import 'graphile-config'
declare global {
// eslint-disable-next-line ts/no-namespace
namespace GraphileBuild {
interface PgResourceTags {
idPrefix?: string
}
interface PgCodecTags {
idPrefix?: string
}
}
}
export default {
name: 'idPrefixNodeIdCodecPlugin',
version: '0.0.1',
description: `Adds our custom node ID codec.`,
schema: {
hooks: {
init(_, build) {
if (!build.registerNodeIdCodec) {
return _
}
const nameToPrefix = new Map<string, string>()
const prefixToName = new Map<string, string>()
for (const codec of Object.values(build.input.pgRegistry.pgCodecs)) {
if (codec.extensions?.tags?.idPrefix) {
const tableTypeName = build.inflection.tableType(codec)
nameToPrefix.set(tableTypeName, codec.extensions.tags.idPrefix)
prefixToName.set(codec.extensions.tags.idPrefix, tableTypeName)
}
}
function encode([name, id]: [string, string]): string | null {
if (!name || !id || id.length !== 26) {
throw new Error(`Invalid nodeIdCodec encode input: ${JSON.stringify([name, id])}`)
}
const prefix = nameToPrefix.get(name) ?? name
return `${prefix}${id}`
}
encode.isSyncAndSafe = true // Optimization
function decode(value: string): [string, string] {
const prefix = value.slice(0, value.length - 26)
const id = value.slice(value.length - 26)
if (!prefix || !id || id.length !== 26)
throw new Error(`Invalid nodeIdCodec decode input: ${JSON.stringify(value)}`)
const name = prefixToName.get(prefix) ?? prefix
return [name, id]
}
decode.isSyncAndSafe = true // Optimization
build.registerNodeIdCodec({
name: 'idPrefix',
encode,
decode,
})
return _
},
},
},
} satisfies GraphileConfig.Plugin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment