@cubicweb/client 1.0.3 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RelationDefinitionSchema = exports.EntitySchema = exports.Schema = exports.getLooseSchema = void 0;
4
+ const Errors_1 = require("../Errors");
5
+ const rawSchemaKey = Symbol("Indexer of the rawSchema");
6
+ /**
7
+ * Returns the given schema using loose typing.
8
+ * Can be useful when working for generic schemas
9
+ *
10
+ * @param schema The schema to create a loose type for
11
+ * @returns
12
+ */
13
+ const getLooseSchema = (schema) => {
14
+ return schema;
15
+ };
16
+ exports.getLooseSchema = getLooseSchema;
17
+ /**
18
+ * Wrapper around the raw JSON Schema
19
+ */
20
+ class Schema {
21
+ constructor(rawSchema) {
22
+ this[rawSchemaKey] = rawSchema;
23
+ }
24
+ get entities() {
25
+ return this[rawSchemaKey].entities.map((eSchema) => new EntitySchema(this, eSchema));
26
+ }
27
+ get relationsDefinitions() {
28
+ return this[rawSchemaKey].relations_definitions.map((rdefSchema) => new RelationDefinitionSchema(this, rdefSchema));
29
+ }
30
+ /**
31
+ * Returns the entity schema for the given entity type if it exists.
32
+ * When using TypeScript, this method can detect if the given type does not exist
33
+ * in the schema.
34
+ *
35
+ * @param entityType The entity type string
36
+ * @returns A new EntitySchema or null if the type does not exist
37
+ */
38
+ getEntity(entityType) {
39
+ const entityRawSchema = this[rawSchemaKey].entities.filter((eSchema) => eSchema.type === entityType)[0];
40
+ if (!entityRawSchema) {
41
+ // Is only null when the given type is not in the schema.
42
+ // Thus the return type will be (EntitySchema | null)
43
+ // but TypeScript does not understand this
44
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
45
+ // @ts-ignore
46
+ return null;
47
+ }
48
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
49
+ // @ts-ignore
50
+ return new EntitySchema(this, entityRawSchema);
51
+ }
52
+ /**
53
+ * Finds relations in the Schema matching the partial relation given
54
+ *
55
+ * @param matcher Partial relation definition to match against
56
+ * @returns Matched relation schema classes
57
+ */
58
+ matchRelationDefinitions(matcher) {
59
+ const matchArray = this[rawSchemaKey].relations_definitions.filter((relDef) => {
60
+ for (const key of Object.keys(matcher)) {
61
+ if (matcher[key] !== relDef[key]) {
62
+ return false;
63
+ }
64
+ }
65
+ return true;
66
+ });
67
+ return matchArray.map((m) => new RelationDefinitionSchema(this, m));
68
+ }
69
+ }
70
+ exports.Schema = Schema;
71
+ /**
72
+ * Wrapper around raw entities from the Schema
73
+ */
74
+ class EntitySchema {
75
+ constructor(schema, entityRawSchema) {
76
+ this.schema = schema;
77
+ this.entityRawSchema = entityRawSchema;
78
+ }
79
+ /**
80
+ * The type of the entity. This can also be referred to as the entity' name.
81
+ */
82
+ get type() {
83
+ return this.entityRawSchema.type;
84
+ }
85
+ /**
86
+ * A short description which can be used as documentation for the entity.
87
+ */
88
+ get description() {
89
+ return this.entityRawSchema.description;
90
+ }
91
+ /**
92
+ * True if the current entity is a primitive type such as string or int
93
+ */
94
+ get final() {
95
+ return this.entityRawSchema.final;
96
+ }
97
+ /**
98
+ * Gets the list of relation definitions with this entity as subject
99
+ */
100
+ get subjectRelationDefinitions() {
101
+ return this.schema.matchRelationDefinitions({
102
+ subject: this.type,
103
+ final: false,
104
+ });
105
+ }
106
+ /**
107
+ * Gets the list of relation definitions with this entity as object
108
+ */
109
+ get objectRelationsDefinitions() {
110
+ return this.schema.matchRelationDefinitions({
111
+ object: this.type,
112
+ final: false,
113
+ });
114
+ }
115
+ /**
116
+ * Finds relations in the Schema matching the partial relation given
117
+ *
118
+ * @param matcher Partial relation definition to match against
119
+ * @returns Matched relation schema classes
120
+ */
121
+ matchRelationDefinitions(matcher) {
122
+ return this.schema.matchRelationDefinitions(matcher);
123
+ }
124
+ /**
125
+ * Gets the list of attributes names for this entity
126
+ */
127
+ get attributes() {
128
+ return this.schema.matchRelationDefinitions({
129
+ final: true,
130
+ subject: this.type,
131
+ });
132
+ }
133
+ }
134
+ exports.EntitySchema = EntitySchema;
135
+ /**
136
+ * Wrapper around raw relation definitions from the Schema
137
+ */
138
+ class RelationDefinitionSchema {
139
+ constructor(schema, relDef) {
140
+ this.schema = schema;
141
+ this.relDef = relDef;
142
+ }
143
+ /**
144
+ * The type of the relation. This can also be referred to as the relation's name.
145
+ */
146
+ get type() {
147
+ return this.relDef.type;
148
+ }
149
+ /**
150
+ * A short description which can be used as documentation for the relation.
151
+ */
152
+ get description() {
153
+ return this.relDef.description;
154
+ }
155
+ /**
156
+ * True if the object of the relation is a primitive type.
157
+ * In this case the relation iscalled an "attribute"
158
+ */
159
+ get final() {
160
+ return this.relDef.final;
161
+ }
162
+ /**
163
+ * The list of constraints if any. Only attributes (relations with final = true) have constraints.
164
+ * In other cases this returns null.
165
+ */
166
+ get constraints() {
167
+ return this.relDef.constraints;
168
+ }
169
+ /**
170
+ * The default value for this relation.
171
+ * It can be used when creating new relations if user did not enter a value (even if required).
172
+ */
173
+ get default() {
174
+ return ("default" in this.relDef ? this.relDef.default : undefined);
175
+ }
176
+ get cardinality() {
177
+ return this.relDef.cardinality;
178
+ }
179
+ get subjectCardinality() {
180
+ return this.relDef.cardinality[0];
181
+ }
182
+ get objectCardinality() {
183
+ return this.relDef.cardinality[1];
184
+ }
185
+ /**
186
+ * Gets the entity associated to this relation's subject
187
+ *
188
+ * @throws InconsistentSchemaError if the relation's subject is not a valid entity
189
+ */
190
+ get subject() {
191
+ const subjectSchema = this.schema.getEntity(this.relDef.subject);
192
+ if (subjectSchema === null) {
193
+ throw new Errors_1.InconsistentSchemaError(`entity type ${this.relDef.subject} used as subject of relation ${this.type} is not declared`);
194
+ }
195
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
196
+ // @ts-ignore
197
+ return subjectSchema;
198
+ }
199
+ /**
200
+ * Gets the entity associated to this relation's object
201
+ *
202
+ * @throws InconsistentSchemaError if the relation's object is not a valid entity
203
+ */
204
+ get object() {
205
+ const objectSchema = this.schema.getEntity(this.relDef.object);
206
+ if (objectSchema === null) {
207
+ throw new Errors_1.InconsistentSchemaError(`entity type ${this.relDef.object} used as object of relation ${this.type} is not declared`);
208
+ }
209
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
210
+ // @ts-ignore
211
+ return objectSchema;
212
+ }
213
+ /**
214
+ * Checks if the relation is required when using the subject or object pointof view
215
+ *
216
+ * @param role The point of view to use
217
+ * @returns
218
+ */
219
+ isRequired(role) {
220
+ let cardinality;
221
+ if (role === "subject") {
222
+ cardinality = this.cardinality[0];
223
+ }
224
+ else {
225
+ cardinality = this.cardinality[1];
226
+ }
227
+ return cardinalityRequired(cardinality);
228
+ }
229
+ }
230
+ exports.RelationDefinitionSchema = RelationDefinitionSchema;
231
+ /**
232
+ * Checks if the given cardinality requires at least one entity to be present
233
+ *
234
+ * @param cardinality The cardinality to check
235
+ * @returns
236
+ */
237
+ function cardinalityRequired(cardinality) {
238
+ return cardinality === "1" || cardinality === "+";
239
+ }
240
+ //# sourceMappingURL=Schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Schema.js","sourceRoot":"","sources":["../../src/schema/Schema.ts"],"names":[],"mappings":";;;AACA,sCAAoD;AAWpD,MAAM,YAAY,GAAkB,MAAM,CAAC,0BAA0B,CAAC,CAAC;AAEvE;;;;;;GAMG;AACI,MAAM,cAAc,GAAG,CAI5B,MAAoB,EACpB,EAAE;IACF,OAAO,MAGN,CAAC;AACJ,CAAC,CAAC;AAVW,QAAA,cAAc,kBAUzB;AAEF;;GAEG;AACH,MAAa,MAAM;IAMjB,YAAY,SAA0B;QACpC,IAAI,CAAC,YAAY,CAAC,GAAG,SAAS,CAAC;IACjC,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,YAAY,CAAC,CAAC,QAAQ,CAAC,GAAG,CACpC,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,YAAY,CAAC,IAAI,EAAE,OAAO,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K,IAAI,EAAE;YACzB,MAAM,IAAI,gCAAuB,CAC/B,eAAe,IAAI,CAAC,MAAM,CAAC,MAAM,+BAA+B,IAAI,CAAC,IAAI,kBAAkB,CAC5F,CAAC;SACH;QACD,6DAA6D;QAC7D,aAAa;QACb,OAAO,YAAY,CAAC;IACtB,CAAC;IAED;;;;;OAKG;IACH,UAAU,CAAC,IAA0B;QACnC,IAAI,WAAwB,CAAC;QAC7B,IAAI,IAAI,KAAK,SAAS,EAAE;YACtB,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,CAAgB,CAAC;SAClD;aAAM;YACL,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,CAAgB,CAAC;SAClD;QACD,OAAO,mBAAmB,CAAC,WAAW,CAAC,CAAC;IAC1C,CAAC;CACF;AAlHD,4DAkHC;AAED;;;;;GAKG;AACH,SAAS,mBAAmB,CAAC,WAAwB;IACnD,OAAO,WAAW,KAAK,GAAG,IAAI,WAAW,KAAK,GAAG,CAAC;AACpD,CAAC"}
@@ -0,0 +1,121 @@
1
+ declare type ConstraintBase<T extends string, V extends Record<string, unknown> | null> = {
2
+ type: T;
3
+ value: V;
4
+ };
5
+ export declare type ConstraintOperator = ">" | ">=" | "<" | "<=";
6
+ declare type ConstraintMessage = string | null;
7
+ export declare type UniqueConstraint = ConstraintBase<"UniqueConstraint", null>;
8
+ export declare type SizeConstraint = ConstraintBase<"SizeConstraint", {
9
+ min: number | null;
10
+ max: number | null;
11
+ msg: ConstraintMessage;
12
+ }>;
13
+ export declare type RegexpConstraint = ConstraintBase<"RegexpConstraint", {
14
+ regexp: string;
15
+ flags: number;
16
+ msg: ConstraintMessage;
17
+ }>;
18
+ export declare type BoundaryConstraint = ConstraintBase<"BoundaryConstraint", {
19
+ boundary: number | null;
20
+ op: ConstraintOperator;
21
+ msg: ConstraintMessage;
22
+ }>;
23
+ export declare type IntervalBoundConstraint = ConstraintBase<"IntervalBoundConstraint", {
24
+ minvalue: number | null;
25
+ maxvalue: number | null;
26
+ msg: ConstraintMessage;
27
+ }>;
28
+ export declare type StaticVocabularyConstraint = ConstraintBase<"StaticVocabularyConstraint", {
29
+ values: string[];
30
+ msg: ConstraintMessage;
31
+ }>;
32
+ export declare type FormatConstraint = ConstraintBase<"FormatConstraint", {
33
+ values: ["text/rest", "text/markdown", "text/html", "text/plain"];
34
+ msg: ConstraintMessage;
35
+ }>;
36
+ export declare type Constraint = Readonly<UniqueConstraint | SizeConstraint | RegexpConstraint | BoundaryConstraint | IntervalBoundConstraint | StaticVocabularyConstraint | FormatConstraint>;
37
+ declare type BuildObjBase<T extends string> = {
38
+ object: T;
39
+ final: true;
40
+ required?: boolean;
41
+ };
42
+ interface StringBuildObj extends BuildObjBase<"String"> {
43
+ default: string | null;
44
+ }
45
+ interface PasswordBuildObj extends BuildObjBase<"Password"> {
46
+ default: string | null;
47
+ }
48
+ interface BytesBuildObj extends BuildObjBase<"Bytes"> {
49
+ default: string | null;
50
+ }
51
+ interface IntBuildObj extends BuildObjBase<"Int"> {
52
+ default: number | null;
53
+ }
54
+ interface BigIntBuildObj extends BuildObjBase<"BigInt"> {
55
+ default: number | null;
56
+ }
57
+ interface FloatBuildObj extends BuildObjBase<"Float"> {
58
+ default: number | null;
59
+ }
60
+ interface BooleanBuildObj extends BuildObjBase<"Boolean"> {
61
+ default: boolean | null;
62
+ }
63
+ interface DecimalBuildObj extends BuildObjBase<"Decimal"> {
64
+ default: number | null;
65
+ }
66
+ interface DateBuildObj extends BuildObjBase<"Date"> {
67
+ default: unknown;
68
+ }
69
+ interface TimeBuildObj extends BuildObjBase<"Time"> {
70
+ default: unknown;
71
+ }
72
+ interface DatetimeBuildObj extends BuildObjBase<"Datetime"> {
73
+ default: Date | "NOW" | "TODAY" | null;
74
+ }
75
+ interface TZTimeBuildObj extends BuildObjBase<"TZTime"> {
76
+ default: unknown;
77
+ }
78
+ interface TZDatetimeBuildObj extends BuildObjBase<"TZDatetime"> {
79
+ default: unknown;
80
+ }
81
+ interface IntervalBuildObj extends BuildObjBase<"Interval"> {
82
+ default: unknown;
83
+ }
84
+ export declare type BuildObj = Readonly<StringBuildObj | PasswordBuildObj | BytesBuildObj | IntBuildObj | BigIntBuildObj | FloatBuildObj | BooleanBuildObj | DecimalBuildObj | DateBuildObj | TimeBuildObj | DatetimeBuildObj | TZTimeBuildObj | TZDatetimeBuildObj | IntervalBuildObj>;
85
+ export declare type Cardinality = "*" | "1" | "?" | "+";
86
+ export declare type CardinalityPair = `${Cardinality}${Cardinality}`;
87
+ export declare type EntityRawSchema = {
88
+ type: string;
89
+ final: boolean;
90
+ description: string;
91
+ };
92
+ export declare type EntityRawSchemaArray = ReadonlyArray<EntityRawSchema>;
93
+ export declare type RelationDefinitionRawSchema<ESchemas extends EntityRawSchemaArray, Final extends boolean = boolean> = Readonly<{
94
+ type: string;
95
+ description: string;
96
+ cardinality: CardinalityPair;
97
+ subject: ESchemas[number]["type"];
98
+ } & (Final extends true ? BuildObj & {
99
+ constraints: Constraint[];
100
+ } : {
101
+ object: EntityRawSchema["type"];
102
+ final: false;
103
+ constraints: null;
104
+ })>;
105
+ export declare type RelationDefinitionRawSchemaArray<ESchemas extends EntityRawSchemaArray> = ReadonlyArray<RelationDefinitionRawSchema<ESchemas, boolean>>;
106
+ export declare type RawSchema<E extends EntityRawSchemaArray = EntityRawSchemaArray, R extends RelationDefinitionRawSchemaArray<E> = RelationDefinitionRawSchemaArray<E>> = {
107
+ entities: E;
108
+ relations_definitions: R;
109
+ };
110
+ export declare type IsLooseSchema<E extends EntityRawSchemaArray> = string extends E[number]["type"] ? true : false;
111
+ export declare type IsETypeInStrictSchema<E extends EntityRawSchemaArray, EType extends string> = EType extends E[number]["type"] ? true : false;
112
+ /**
113
+ * Type representing the entity's raw schema matching this type.
114
+ * This type only works for EntityRawSchemaArray with literals as "type" property.
115
+ *
116
+ **/
117
+ export declare type EntityRawSchemaByType<E extends EntityRawSchemaArray, T extends string> = E[number] extends infer ESchema ? ESchema extends {
118
+ type: T;
119
+ } ? ESchema : never : never;
120
+ export {};
121
+ //# sourceMappingURL=SchemaJSON.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SchemaJSON.d.ts","sourceRoot":"","sources":["../../src/schema/SchemaJSON.ts"],"names":[],"mappings":"AAAA,aAAK,cAAc,CACjB,CAAC,SAAS,MAAM,EAChB,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,IACtC;IACF,IAAI,EAAE,CAAC,CAAC;IACR,KAAK,EAAE,CAAC,CAAC;CACV,CAAC;AAEF,oBAAY,kBAAkB,GAAG,GAAG,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,CAAC;AACzD,aAAK,iBAAiB,GAAG,MAAM,GAAG,IAAI,CAAC;AAEvC,oBAAY,gBAAgB,GAAG,cAAc,CAAC,kBAAkB,EAAE,IAAI,CAAC,CAAC;AAExE,oBAAY,cAAc,GAAG,cAAc,CACzC,gBAAgB,EAChB;IAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,GAAG,EAAE,iBAAiB,CAAA;CAAE,CACnE,CAAC;AAEF,oBAAY,gBAAgB,GAAG,cAAc,CAC3C,kBAAkB,EAClB;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,iBAAiB,CAAA;CAAE,CAC1D,CAAC;AAEF,oBAAY,kBAAkB,GAAG,cAAc,CAC7C,oBAAoB,EACpB;IAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,EAAE,EAAE,kBAAkB,CAAC;IAAC,GAAG,EAAE,iBAAiB,CAAA;CAAE,CAC5E,CAAC;AACF,oBAAY,uBAAuB,GAAG,cAAc,CAClD,yBAAyB,EACzB;IAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;I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ACJ,oBAAY,qBAAqB,CAC/B,CAAC,SAAS,oBAAoB,EAC9B,CAAC,SAAS,MAAM,IACd,CAAC,CAAC,MAAM,CAAC,SAAS,MAAM,OAAO,GAC/B,OAAO,SAAS;IAAE,IAAI,EAAE,CAAC,CAAA;CAAE,GACzB,OAAO,GACP,KAAK,GACP,KAAK,CAAC"}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=SchemaJSON.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SchemaJSON.js","sourceRoot":"","sources":["../../src/schema/SchemaJSON.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@cubicweb/client",
3
3
  "description": "Official JS client for CubicWeb API",
4
4
  "author": "Logilab",
5
- "version": "1.0.3",
5
+ "version": "1.1.1",
6
6
  "license": "LGPL-3.0-or-later",
7
7
  "main": "lib/index.js",
8
8
  "types": "lib/index.d.ts",
package/src/Errors.ts CHANGED
@@ -5,19 +5,6 @@ export class InconsistentSchemaError extends Error {
5
5
  }
6
6
  }
7
7
 
8
- export class RelationNotFoundError extends Error {
9
- constructor(
10
- relationType: string,
11
- role: "object" | "subject",
12
- entityType: string
13
- ) {
14
- super(
15
- `Relation Not Found: relation type ${relationType} with entity type ${entityType} as ${role} is not declared`
16
- );
17
- Object.setPrototypeOf(this, new.target.prototype);
18
- }
19
- }
20
-
21
8
  export class TransactionClosedError extends Error {
22
9
  constructor() {
23
10
  super("Trying to use a closed transaction");
package/src/api/Api.ts CHANGED
@@ -22,8 +22,8 @@ export default class Api {
22
22
  this.transactionApiUrl = `${this.apiUrl}/transaction`;
23
23
  }
24
24
 
25
- async execute(query: string, params: RQLParams) {
26
- return fetchApi(`${this.apiUrl}/rql`, {
25
+ async execute(query: string, params: RQLParams): Promise<ResultSet> {
26
+ return nonNullFetchApi<ResultSet>(`${this.apiUrl}/rql`, {
27
27
  method: "POST",
28
28
  body: JSON.stringify({ query, params }),
29
29
  credentials: "include", // FIXME is it secure?
@@ -31,58 +31,105 @@ export default class Api {
31
31
  }
32
32
 
33
33
  async schema(): Promise<RawSchema> {
34
- const res = await fetch(`${this.apiUrl}/schema`);
35
- const schema = await res.json();
36
- return schema as RawSchema;
34
+ return nonNullFetchApi<RawSchema>(`${this.apiUrl}/schema`, {
35
+ method: "GET",
36
+ credentials: "include",
37
+ });
38
+ }
39
+
40
+ async login(login: string, password: string): Promise<boolean> {
41
+ return fetchApi<null>(`${this.apiUrl}/login`, {
42
+ method: "POST",
43
+ body: JSON.stringify({
44
+ login,
45
+ password,
46
+ }),
47
+ credentials: "include",
48
+ })
49
+ .then(() => true)
50
+ .catch(() => false);
37
51
  }
38
52
 
39
- async transactionBegin() {
40
- const body = JSON.stringify({ action: "begin" });
41
- return await fetch(this.transactionApiUrl, {
53
+ async transactionBegin(): Promise<string> {
54
+ return nonNullFetchApi<string>(this.transactionApiUrl, {
42
55
  method: "POST",
43
- body,
56
+ body: JSON.stringify({ action: "begin" }),
44
57
  credentials: "include",
45
58
  });
46
59
  }
47
60
 
48
- async transactionExecute(uuid: string, query: string, params: RQLParams) {
49
- const body = JSON.stringify({ action: "execute", uuid, query, params });
50
- return fetchApi(this.transactionApiUrl, {
61
+ async transactionExecute(
62
+ uuid: string,
63
+ query: string,
64
+ params: RQLParams
65
+ ): Promise<ResultSet> {
66
+ return nonNullFetchApi<ResultSet>(this.transactionApiUrl, {
51
67
  method: "POST",
52
- body,
68
+ body: JSON.stringify({ action: "execute", uuid, query, params }),
53
69
  credentials: "include",
54
70
  });
55
71
  }
56
72
 
57
- async transactionCommit(uuid: string) {
58
- const body = JSON.stringify({ action: "commit", uuid });
59
- return await fetch(this.transactionApiUrl, {
73
+ async transactionCommit(uuid: string): Promise<null> {
74
+ return fetchApi<null>(this.transactionApiUrl, {
60
75
  method: "POST",
61
- body,
76
+ body: JSON.stringify({ action: "commit", uuid }),
62
77
  credentials: "include",
63
78
  });
64
79
  }
65
80
 
66
- async transactionRollback(uuid: string) {
67
- const body = JSON.stringify({ action: "commit", uuid });
68
- return await fetch(this.transactionApiUrl, {
81
+ async transactionRollback(uuid: string): Promise<null> {
82
+ return fetchApi<null>(this.transactionApiUrl, {
69
83
  method: "POST",
70
- body,
84
+ body: JSON.stringify({ action: "commit", uuid }),
71
85
  credentials: "include",
72
86
  });
73
87
  }
74
88
  }
75
89
 
76
- export const fetchApi = (input: RequestInfo, init?: RequestInit) => {
90
+ const nonNullFetchApi = <R = unknown>(
91
+ input: RequestInfo,
92
+ init?: RequestInit
93
+ ) => {
94
+ return new Promise(
95
+ (resolve: (value: R) => void, reject: (reason: ApiErrorResponse) => void) =>
96
+ fetchApi<R>(input, init)
97
+ .then((v) => {
98
+ if (v == null) {
99
+ const error: ApiErrorResponse = {
100
+ status: 500,
101
+ error: "Unexpected null response",
102
+ message: "Response was null but a value was expected",
103
+ };
104
+ reject(error);
105
+ } else {
106
+ resolve(v);
107
+ }
108
+ })
109
+ .catch(reject)
110
+ );
111
+ };
112
+
113
+ const fetchApi = <R = unknown>(input: RequestInfo, init?: RequestInit) => {
77
114
  return new Promise(
78
115
  (
79
- resolve: (value: ResultSet) => void,
116
+ resolve: (value: R | null) => void,
80
117
  reject: (reason: ApiErrorResponse) => void
81
118
  ) =>
82
119
  fetch(input, init).then((response) => {
83
120
  const status = response.status;
84
- if (status === 200) {
85
- response.json().then(resolve);
121
+ if (status >= 200 && status < 300) {
122
+ if (status === 204) {
123
+ resolve(null);
124
+ } else {
125
+ response
126
+ .json()
127
+ .then(resolve)
128
+ .catch((e) => {
129
+ console.error(e);
130
+ resolve(null);
131
+ });
132
+ }
86
133
  } else {
87
134
  response.json().then((data: ApiError) => {
88
135
  reject({
package/src/api/Client.ts CHANGED
@@ -13,11 +13,15 @@ export default class Client {
13
13
  return await this.api.execute(query, params);
14
14
  }
15
15
 
16
- async schema(): Promise<Schema> {
16
+ async schema() {
17
17
  const schema = await this.api.schema();
18
18
  return new Schema(schema);
19
19
  }
20
20
 
21
+ async login(login: string, password: string) {
22
+ return await this.api.login(login, password);
23
+ }
24
+
21
25
  async transaction<T>(callback: (tr: Transaction) => Promise<T>): Promise<T> {
22
26
  const transaction = new Transaction(this.api);
23
27
  await transaction.begin();
@@ -17,9 +17,7 @@ export default class Transaction {
17
17
 
18
18
  async begin() {
19
19
  this._closed = false;
20
- const response = await this.api.transactionBegin();
21
- const json = await response.json();
22
- this._uuid = json;
20
+ this._uuid = await this.api.transactionBegin();
23
21
  }
24
22
 
25
23
  async execute(query: string, params: RQLParams = {}) {