ChatiumFor developersPlaygroundPricing
Sign in

HeapTableRepo.createOrUpdateBy

Allows for the atomic creation of a record with a specified unique key or updating it if a record with that key value already exists. The overall logic can be described as follows:

  • If there are no records in the table with the specified key value, a new record is created with the given field values and default field values filled in (as in create).

  • If there is a record in the table with the specified key value and it is the only one, the field values of that record are updated according to the provided object (as in update).

  • If there are multiple records in the table with the specified key value, an appropriate error is thrown, and no changes occur. The values of the provided fields are validated against the table schema.

Using the createOrUpdateBy method guarantees that no duplicate records will be created in the table based on the selected key. However, it should be understood that this guarantee only applies if the createOrUpdateBy method is used exclusively for creating records in this table and create is never used.

Usage/Signature

table.createOrUpdateBy(ctx, uniqFieldName, fields)

Arguments

  • ctx*: app.Ctx
    Request context. Used for internal implementation, saving information about the user who modified the record, and allows executing the request in the necessary transaction.
  • uniqFieldName: string
    The name of the top-level field from the table schema, the value of which is used as a unique key for this operation. The field must have a type that supports filtering by exact value (see query language guide).
  • fields: { [uniqFieldName], ... }
    An object with fields and values corresponding to the table schema. The object must define the value of the field corresponding to uniqFieldName, as well as all "required" fields declared in the heap table schema: all except Optional, Nullable, and NonRequired, just like in create.

<!-- TODO create -->

Return Value: Promise<HeapObject>

The newly created or modified heap object.

Examples


Creating a unique record with additional information about the current user. In both calls to createOrUpdateBy, the same record is being worked with.

const UserInfos = Heap.Table('userInfos', {
  userId: Heap.RefLink('users'),
  occupation: Heap.Optional(Heap.String()),
  religion: Heap.Optional(Heap.String()),
})

const info1 = await UserInfos.createOrUpdateBy(ctx, 'userId', {
  userId: ctx.user.id,
  occupation: 'Software Developer',
})
const info2 = await UserInfos.createOrUpdateBy(ctx, 'userId', {
  userId: ctx.user.id,
  religion: 'Agnostic',
})
// info1.id === info2.id