Deepkit ORM // Examples

Handle unique constraint violation

Back to all Deepkit ORM examples
import {entity, PrimaryKey, Database, Unique} from "@deepkit/type";
import {Database, UniqueConstraintFailure} from '@deepkit/orm';

@entity.collection('users')
class User {
    id: number & PrimaryKey = 0;
    constructor(public username: string & Unique) {}
}

async function addUser(data: Partial<User>, database: Database) {
    const user = cast<User>(data);

    try {
        await database.persist(user);
    } catch (error: any) {
        if (error instanceof UniqueConstraintFailure) {
            throw new Error('Username already taken');
        }
        throw error;
    }
}