Using in the Browser

Note

Starting from version 4.5.0, Records.get and Records.query can be used instead of Citeck.Records.get and Citeck.Records.query.

The Records component has been developed for working with the Records API and is available in the global context on any page of the system.

Available operations:

  • get(recordRef) — Retrieve a record by its identifier. The list of operations on a record is provided below;

  • query(query, attributes) — Search for records. The first argument is the search query, and the second is which attributes are needed from the found records;

  • remove(records) — Delete records.

Operations on a record retrieved via the “Records.get” method:

  • load(attributes, forceLoad) — Load one or more attributes. The first argument specifies what to load, and the second specifies whether to use the cache. The second argument is optional and defaults to false (i.e. cache is active);

  • att(attributeName, value) — Set the value of an attribute for a record. Used before saving the record;

  • save(attsToLoad) — Save the changes made to the record via the att method from the previous item and load the attributes passed in attsToLoad (optional);

Starting from UI version 2.8.1, the save method can accept attributes to load. In this case, the attributes to load are also sent to the server along with the attributes to modify, in the attributes field of the request body. If load attributes are specified when calling save, the result will have the same format as when calling the load method.

Query structure

{
  "sourceId": String // идентификатор источника данных в формате "приложение/id_локального_источника_данных"
  "query": Any // любой формат, который поддерживается источником данных
  "language": String // язык для определения содержимого query. Источник данных может поддерживать несколько языков
  "sortBy": [
      {
          "attribute": String // атрибут для сортировки
          "ascending": Boolean // сортировка должна быть по возрастанию true или по убыванию false
      }
  ],
  "groupBy": [String] // список атрибутов для группировки
  "page": {
      maxItems: Number // максимальное кол-во элементов
      skipCount: Number // количество элементов, которое нужно пропустить при поиске
  }
  "consistency": EVENTUAL | TRANSACTIONAL | DEFAULT | TRANSACTIONAL_IF_POSSIBLE // ожидаемая консистенция данных. EVENTUAL позволяет использовать индексы для поиска элементов
}

Usage examples

// Запрос ФИО пользователя:

var user = Records.get('emodel/person@user');
await user.load(['userName', 'firstName', 'lastName'])

// Запрос имени пользователя:

var user = Records.get('emodel/person@user')
await user.load('firstName')

// Пример скрипта для смены статуса:

var doc = Records.get('someDocumentRef');
doc.att('_status', 'some_status_id');
doc.save();

// Получение сразу нескольких атрибутов у вложенного значения:

await Records.get('uiserv/rjournal@test587').load(boardRefs[]{id,name}, true)

// Статус объекта:

await Records.get('emodel/someType@id').load("_status?str")

// Проверка enterprise лицензии:

await Records.get('emodel/meta@').load('$license.enterprise?bool', true)

// Получения рабочих областей текущего пользователя:

await Records.query({
    sourceId: 'emodel/workspace',
    language: 'user-workspaces'
}, {
    'wsId': '?localId',
    'wsName': '?disp!?localId'
})

// Узнать sourceId по typeId:

await Records.get('emodel/type@typeId').load('sourceId')

CRUD operations

Below are examples of the basic operations performed when managing and manipulating data:

const record = Records.get("emodel/someType@");
record.att("name", "New record");
record.att("someAttribute", "Hello world!");
record.save();
const record = Records.getRecordToEdit("emodel/someType@id");
await record.load("?json");
const record = Records.getRecordToEdit("emodel/someType@id");
record.att("someAttribute", "New value");
record.save();
Records.remove("emodel/someType@id1"); // 1 объект
Records.remove(["emodel/someType@id1", "emodel/someType@id2"]); // массив объектов

Communication with the server occurs via POST requests:

Request

Description

Used in ecos-ui code

READ_ONLY POST

/gateway/api/records/query

Searching records and/or retrieving attributes

Records.query и Records.get("id_сущности").load(атрибуты_для_загрузки)

READ_WRITE POST

/gateway/api/records/delete

Deleting entities

Records.remove

READ_WRITE POST

/gateway/api/records/mutate

Creating or modifying entities

var rec = Records.get("id_сущности"); rec.att("атрибут", "значение"); rec.save()

Response return types

Only the JSON type can be returned in the response.

HTTP response codes

Possible response codes:

  • 200 OK

  • 401 Unauthorized

  • 500 Internal Server Error

Error descriptions and their levels

Errors are reflected in the response body under the messages key with the level field equal to “ERROR”.

Example:

{
  "messages": [
    {
      "level": "ERROR",
      "time": 1653990549261,
      "type": "text",
      "msg": "Some error",
      "requestId": "7848a70e-a449-4b24-abb9-a2a7fbb8ebfa",
      "requestTrace": [
        "gateway:06d039e1766550be603cf98379bbdb22",
        "alfresco:019ca5db-160f-45df-84a6-02750a4f13b7"
      ]
    }
  ],
  "txnActions": [],
  "records": [],
  "hasMore": false,
  "totalCount": 0,
  "version": 1
}

The only available level is “ERROR”.