Skip to content

Bring Your Own ID

Compare
Choose a tag to compare
@mdwheele mdwheele released this 16 Sep 03:43
· 25 commits to master since this release
a72cfc2

You can now configure your own strategy for how model identifiers are generated. By default, we delegate to your DBMS of choice to assign a unique identifier. However, there are times when you want to use UUID, ULID, or other identifier strategies that might not be supported by your flavor of SQL.

Let's take a look at an example where we have our own custom libraries for ID generation that have been used for years.

import { generateId } from '../lib/util.js'

class Legacy extends Model {
  // First, we have a custom primary key name
  identity

  // So we have to tell YORM about that
  get primaryKey() { return 'identity' }

  // "Somebody" wrote a utility to generate totally 
  // secure IDs like 12 years ago and we're stuck using them.
  // No worries, just set up the `newUniqueId` accessor!
  get newUniqueId() {
    return generateId()
  }
}

// Every time an instance is created, it will automatically 
// generate an ID following our "legacy" strategy

Legacy.make().identity  // '0-384-388385-A'

If you want to use UUID, ULID, or nanoid identifiers, return 'uuid', 'ulid', or 'nanoid', respectively.

class ULID extends Model {
  id

  get newUniqueId() {
    return 'ulid'  // '01F7DKCVCVDZN1Z5Q4FWANHHCC'
  }
}

As usual, if you provide an ID during the construction of an instance within a .make(...) or .create(...) call, that will override any sort of generation that occurs.