Skip to content

Instantly share code, notes, and snippets.

@stephenlacy
Created July 1, 2024 23:13
Show Gist options
  • Save stephenlacy/9ac873341ab00fe3fe15b8acf40ec32f to your computer and use it in GitHub Desktop.
Save stephenlacy/9ac873341ab00fe3fe15b8acf40ec32f to your computer and use it in GitHub Desktop.
Using TypeIDs with Drizzle
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 }),
}
);
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