Created
July 1, 2024 23:13
-
-
Save stephenlacy/9ac873341ab00fe3fe15b8acf40ec32f to your computer and use it in GitHub Desktop.
Using TypeIDs with Drizzle
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
export const apiKeys = mysqlTable( | |
"api_keys", | |
{ | |
id: typeId("api_keys").primaryKey(), | |
organizationId: typeId("organizations", "organization_id").notNull(), | |
name: varchar("name", { length: 256 }), | |
prefix: varchar("prefix", { length: 256 }), | |
} | |
); |
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
import { TypeID } from "typeid-js"; | |
import { customType } from "drizzle-orm/mysql-core"; | |
export const typeId = (name: string, column: string = "id") => { | |
return customType<{ | |
data: string; | |
notNull: true; | |
}>({ | |
dataType: () => { | |
return "varchar(36)"; | |
}, | |
fromDriver: (val: unknown) => { | |
const parsed = TypeID.fromUUID(name, val as string); | |
return parsed.toString(); | |
}, | |
toDriver: (val) => { | |
const parsed = TypeID.fromString(val).toUUID(); | |
return parsed; | |
}, | |
})(column).notNull().$defaultFn(() => typeid(name).toString()) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment