Type-Specific Identifier Generation

In the previous article, Global Identifier generation conventions were introduced. Any customization made by using those conventions changes the behavior for all stored entities. Now we will show how to override the default ID generation in a more granular way, for particular types of entities.

To override default document identifier generation algorithms, you can register custom conventions per an entity type. You can include your own identifier generation logic.

RegisterIdConvention

conventions.registerIdConvention(clazz, idConvention);
Parameters
clazz class or object Entity type
idConvention function (databaseName, entity) => Promise<string> Identifier generation function that supplies a result for given database name and entity object. Must return a Promise resolving to a string.
Return Value
DocumentConventions Current DocumentConventions instance.

Database name parameter

The database name parameter is passed to the register convention methods to allow users to make Id generation decision per database.

Example

Let's say that you want to use semantic identifiers for Employee objects. Instead of employee/[identity] you want to have identifiers like employees/[lastName]/[firstName] (for the sake of simplicity, let us not consider the uniqueness of such identifiers). What you need to do is to create the convention that will combine the employee prefix, LastName and FirstName properties of an employee.

store.conventions.registerIdConvention(Employee,
    (dbName, entity) => Promise.resolve(`employees/${entity.lastName}/${entity.firstName}`)); 

// or using async keyword
store.conventions.registerIdConvention(Employee,
    async (dbName, entity) => `employees/${entity.lastName}/${entity.firstName}`); 

Now, when you store a new entity:

const session = store.openSession();
const employee = new Employee("James", "Bond");

await session.store(employee);
await session.saveChanges();

the client will associate the employees/Bond/James identifier with it.

Information

ID convention function must return a Promise since it can be asynchronous.

Example: Object literal based entities

// for object literal based entities you can pass type descriptor object
const typeDescriptor = {
    name: "Employee",
    isType(entity) {
        // if it quacks like a duck... ekhm employee
        return entity 
            && "firstName" in entity 
            && "lastName" in entity 
            && "boss" in entity;
    }
};

store.conventions.registerIdConvention(typeDescriptor, 
    async (dbName, entity) => `employees/${entity.lastName}/${entity.firstName}`);