Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there a way of generating nanoids through the ESDL file? #1010

Open
psygo opened this issue May 7, 2024 · 2 comments
Open

Is there a way of generating nanoids through the ESDL file? #1010

psygo opened this issue May 7, 2024 · 2 comments

Comments

@psygo
Copy link

psygo commented May 7, 2024

I would like to have an extra, short nanoid for one of my tables. How do I do that? Is it possible to do it through the .esdl file?

On Drizzle, for example, I do something like this:

import { nanoid } from "nanoid"

...

nanoId: varchar("nano_id", { length: 256 })
  .unique()
  .notNull()
  .$defaultFn(() => nanoid()),

That's TypeScript, but there are PostgreSQL implementations of it, like viascom/nanoid-postgres.

Anyway, my question is not about nanoid specifically, but about how to do a custom ID.

@scotttrinh
Copy link
Collaborator

nanoid is just a string at the type level, right? We don't expose a way to create random types at the database level (it would need to be something implemented like the pg extension), but you absolutely can create one in your data layer that inserts objects. Rough sketch:

function createFoo(data) {
  return e.insert(e.Foo, {
    nano_id: nanoid(),
    ...data,
  }).run(client);
}

Making this a generic helper is left as an exercise for the reader 😅 I'd probably just have some function that inserts a nanoid at a default (overridable) key in a source object to abstract out the nanoid insertion. Or really, I'd just do it inline in the places I want them.

It's on our medium-term radar to add some higher level wrappers for doing more generic/abstract things that go beyond just mapping EdgeQL to TypeScript, and we'd probably want to have some similar thing affordance within that context in the future.

@psygo
Copy link
Author

psygo commented May 7, 2024

Thank you for the quick response!

It's just that I find Drizzle's option of setting up custom functions from TypeScript incredibly practical, and it helps cleaning up the code quite a bit to setup defaults like that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants