Skip to content

Snippets: Assets

These are the snippets the console’s Snippets dialog offers under Assets. Each is TypeScript; in a .js script the console shows the same code with its types removed. Every one runs unchanged in Code Studio’s own tests. How the API they call behaves is in writing scripts and the script API reference.

Create an Assets object

Creates an object of a type with its attributes by attribute id. Find both ids on the object type’s Attributes page in Assets, and keep them in script variables.

interface CreatedObject {
id: string;
objectKey: string;
}
export default async function (event: unknown, context: ScriptContext) {
const vars = context.environment.vars;
const created = await assets.post<CreatedObject>('/object/create', {
objectTypeId: vars.LAPTOP_TYPE_ID ?? '1',
attributes: [
{ objectTypeAttributeId: vars.NAME_ATTRIBUTE_ID ?? '2', objectAttributeValues: [{ value: 'LAPTOP-0042' }] },
{ objectTypeAttributeId: vars.SERIAL_ATTRIBUTE_ID ?? '3', objectAttributeValues: [{ value: 'C02XK1ZZJG5H' }] },
],
});
log.info(`Created ${created.objectKey}`);
return { id: created.id, key: created.objectKey };
}

Update an Assets object

Sets one attribute on an object by its id. Attributes not named keep their values.

export default async function (event: unknown, context: ScriptContext) {
const vars = context.environment.vars;
const objectId = vars.OBJECT_ID ?? '1';
await assets.put(`/object/${objectId}`, {
attributes: [{ objectTypeAttributeId: vars.STATUS_ATTRIBUTE_ID ?? '4', objectAttributeValues: [{ value: 'In use' }] }],
});
return { objectId };
}

Find Assets objects with AQL

Reads every object an AQL query finds, page by page, until Assets says it is the last one.

interface AqlPage {
values: { id: string; objectKey: string; label: string }[];
isLast: boolean;
}
export default async function () {
const found: string[] = [];
for (let startAt = 0; ; startAt += 50) {
const page = await assets.post<AqlPage>('/object/aql', { qlQuery: 'objectType = Laptop AND Status = "In use"' }, { query: { startAt, maxResults: 50 } });
found.push(...page.values.map((object) => object.objectKey));
if (page.isLast || page.values.length === 0) break;
}
return { count: found.length, first: found.slice(0, 10) };
}

Delete an Assets object

Deletes one object by its id. Work items that referred to it lose the reference.

export default async function (event: unknown, context: ScriptContext) {
const objectId = context.environment.vars.OBJECT_ID;
if (!objectId) throw new Error('Set OBJECT_ID to the object to delete.');
await assets.delete(`/object/${objectId}`);
return { deleted: objectId };
}

A problem or a question? Write to support@oktul.com or open a request in the Help Center (opens in a new tab). Both reach the same service desk, so either way the request gets a reference and an SLA measuring the response.