2022-09-21 08:08:25 +00:00
|
|
|
import core, { AnyAttribute, Class, Client, Doc, Ref, TxOperations } from '@hcengineering/core'
|
2021-12-30 09:04:32 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @public
|
|
|
|
*/
|
|
|
|
export interface KeyedAttribute {
|
|
|
|
key: string
|
|
|
|
attr: AnyAttribute
|
|
|
|
}
|
|
|
|
|
2022-04-29 05:27:17 +00:00
|
|
|
export async function updateAttribute (
|
|
|
|
client: TxOperations,
|
|
|
|
object: Doc,
|
|
|
|
_class: Ref<Class<Doc>>,
|
|
|
|
attribute: KeyedAttribute,
|
|
|
|
value: any
|
|
|
|
): Promise<void> {
|
2021-12-30 09:04:32 +00:00
|
|
|
const doc = object
|
|
|
|
const attributeKey = attribute.key
|
2022-05-22 11:07:02 +00:00
|
|
|
if ((doc as any)[attributeKey] === value) return
|
2021-12-30 09:04:32 +00:00
|
|
|
const attr = attribute.attr
|
|
|
|
if (client.getHierarchy().isMixin(attr.attributeOf)) {
|
|
|
|
await client.updateMixin(doc._id, _class, doc.space, attr.attributeOf, { [attributeKey]: value })
|
|
|
|
} else {
|
2022-06-08 13:55:01 +00:00
|
|
|
if (client.getHierarchy().isDerived(attribute.attr.type._class, core.class.ArrOf)) {
|
|
|
|
const oldvalue: any[] = (object as any)[attributeKey] ?? []
|
|
|
|
const val: any[] = value
|
|
|
|
const toPull = oldvalue.filter((it: any) => !val.includes(it))
|
|
|
|
|
|
|
|
const toPush = val.filter((it) => !oldvalue.includes(it))
|
|
|
|
if (toPull.length > 0) {
|
|
|
|
await client.update(object, { $pull: { [attributeKey]: { $in: toPull } } })
|
|
|
|
}
|
|
|
|
if (toPush.length > 0) {
|
|
|
|
await client.update(object, { $push: { [attributeKey]: { $each: toPush, $position: 0 } } })
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
await client.update(object, { [attributeKey]: value })
|
|
|
|
}
|
2021-12-30 09:04:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getAttribute (client: Client, object: any, key: KeyedAttribute): any {
|
|
|
|
// Check if attr is mixin and return it's value
|
|
|
|
if (client.getHierarchy().isMixin(key.attr.attributeOf)) {
|
2022-04-29 05:27:17 +00:00
|
|
|
return object[key.attr.attributeOf]?.[key.key]
|
2021-12-30 09:04:32 +00:00
|
|
|
} else {
|
|
|
|
return object[key.key]
|
|
|
|
}
|
|
|
|
}
|