forked from teambit/bit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent-objects.ts
More file actions
73 lines (62 loc) · 2.3 KB
/
component-objects.ts
File metadata and controls
73 lines (62 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { toBase64ArrayBuffer } from '../utils';
import ModelComponent from './models/model-component';
import BitObject from './objects/object';
export default class ComponentObjects {
component: Buffer;
objects: Buffer[];
constructor(component: Buffer, objects: Buffer[]) {
this.component = component;
this.objects = objects;
}
toString(): string {
return JSON.stringify({
component: toBase64ArrayBuffer(this.component),
objects: this.objects.map(toBase64ArrayBuffer),
});
}
// Used mainly by server side hooks
getParsedComponent(): BitObject {
const component = BitObject.parseSync(this.component);
return component;
}
// @TODO optimize ASAP.
static fromString(str: string): ComponentObjects {
return ComponentObjects.fromObject(JSON.parse(str));
}
static manyToString(componentsAndObjects: Array<{ component: Buffer; objects: Buffer[] }>) {
const result = JSON.stringify(componentsAndObjects.map((componentAndObject) => componentAndObject.toString()));
return result;
}
static manyFromString(str: string): ComponentObjects[] {
return JSON.parse(str).map((componentObject) => ComponentObjects.fromString(componentObject));
}
static fromObject(object: Record<string, any>): ComponentObjects {
// @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
// @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
const { component, objects } = object;
return new ComponentObjects(_from64Buffer(component), objects.map(_from64Buffer));
}
/**
* prefer using `this.toObjectsAsync()` if not must to be sync.
*/
toObjects(): { component: ModelComponent; objects: BitObject[] } {
return {
// @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
component: BitObject.parseSync(this.component),
objects: this.objects.map((obj) => BitObject.parseSync(obj)),
};
}
/**
* see `this.toObject()` for the sync version
*/
async toObjectsAsync(): Promise<{ component: ModelComponent; objects: BitObject[] }> {
return {
// @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
component: await BitObject.parseObject(this.component),
objects: await Promise.all(this.objects.map((obj) => BitObject.parseObject(obj))),
};
}
}
function _from64Buffer(val): Buffer {
return Buffer.from(val, 'base64');
}