deepkit / deepkit-framework

A new full-featured and high-performance TypeScript framework
https://deepkit.io/
MIT License
3.2k stars 123 forks source link

Support for CUID and NanoId #419

Open jackgdll opened 1 year ago

jackgdll commented 1 year ago

Could support for CUIDs and NanoIds be added? Can be used in the same way as uuid:

import { cuid, CUID, NanoId, nanoId, PrimaryKey } from '@deepkit/type';

class User {
    cuid: CUID & PrimaryKey = cuid();
    // Or the following
    // nanoId: NanoID & PrimaryKey = nanoId();
}

This would be nice to have to shorten ids.

marcj commented 1 year ago

I think string would be enough, no?

class User {
    cuid: string & PrimaryKey = cuid();
}
jackgdll commented 1 year ago

I guess so, it wouldn't be able to validate the field though would it?

The @paralleldrive/cuid2 package exposes an isCuid function so it should be trivial to add validation if I'm not mistaken?

import { createId, isCuid } from '@paralleldrive/cuid2';

console.log(
  isCuid(createId()), // true
  isCuid('not a cuid'), // false
);
marcj commented 1 year ago

True, no validation happens. When we add a new type like CUID we can add validation logic like so https://github.com/deepkit/deepkit-framework/blob/master/packages/type/src/serializer.ts#L1865-L1871 and https://github.com/deepkit/deepkit-framework/blob/master/packages/type/src/serializer.ts#L2050-L2054