@dnv-plant/typescriptpws 1.0.0-alpha.0

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,537 @@
1
+ /***********************************************************************
2
+ * This file has been auto-generated by a code generation tool.
3
+ * Version: 1.0.0
4
+ * Date/time: 30 Jan 2025 10:12:17
5
+ * Template: templates/typescriptpws/materials.razor.
6
+ ***********************************************************************/
7
+
8
+ import {
9
+ getRequest,
10
+ postRequest,
11
+ putRequest,
12
+ getMaterialsApiTarget,
13
+ getClientAliasId,
14
+ } from "./utilities";
15
+ import { MaterialSchema, MaterialComponentDataSchema } from "./entity-schemas";
16
+ import { Material, MaterialComponentData } from "./entities";
17
+
18
+ import Joi from "joi";
19
+
20
+ interface SchemaClass {
21
+ schema: Joi.ObjectSchema; // The class must have a `schema` property of type Joi.ObjectSchema
22
+ }
23
+
24
+ export class MaterialInfo {
25
+ /**
26
+ * MaterialInfo class.
27
+ *
28
+ * @param {string} id - A unique identifier of the material.
29
+ * @param {string} name - The name of the material.
30
+ */
31
+ constructor(readonly id: string, readonly name: string) {}
32
+ }
33
+
34
+ export class MaterialCasIdInfo {
35
+ /**
36
+ * MaterialCasIdInfo class.
37
+ *
38
+ * @param {string} id - A unique identifier of the material.
39
+ * @param {string} name - The name of the material.
40
+ * @param {string} casId - The CAS ID of the material.
41
+ */
42
+ constructor(
43
+ readonly id: string,
44
+ readonly name: string,
45
+ readonly casId: string
46
+ ) {}
47
+ }
48
+
49
+ export class MaterialInfoSchema {
50
+ schema: Joi.ObjectSchema;
51
+
52
+ constructor() {
53
+ this.schema = Joi.object({
54
+ id: Joi.string().guid({ version: "uuidv4" }).required(),
55
+ displayName: Joi.string().required(),
56
+ }).unknown(true);
57
+ }
58
+
59
+ /**
60
+ * Validates and transforms data into a MaterialInfo object.
61
+ * @param data - The input data to validate and transform.
62
+ * @returns A MaterialInfo instance.
63
+ * @throws Error if validation fails.
64
+ */
65
+ makeMaterialInfo(data: { id: string; displayName: string }): MaterialInfo {
66
+ const { error, value } = this.schema.validate(data);
67
+ if (error) {
68
+ throw new Error(`Validation error: ${error.details[0].message}`);
69
+ }
70
+ return new MaterialInfo(value.id, value.displayName);
71
+ }
72
+ }
73
+
74
+ export class MaterialCasIdInfoSchema {
75
+ schema: Joi.ObjectSchema;
76
+
77
+ constructor() {
78
+ this.schema = Joi.object({
79
+ id: Joi.string().guid({ version: "uuidv4" }).required(),
80
+ name: Joi.string().required(),
81
+ casId: Joi.string().required(),
82
+ }).unknown(true);
83
+ }
84
+
85
+ /**
86
+ * Validates and transforms data into a MaterialCasIdInfo object.
87
+ * @param data - The input data to validate and transform.
88
+ * @returns A MaterialCasIdInfo instance.
89
+ * @throws Error if validation fails.
90
+ */
91
+ makeMaterialInfo(data: {
92
+ id: string;
93
+ name: string;
94
+ casId: string;
95
+ }): MaterialCasIdInfo {
96
+ const { error, value } = this.schema.validate(data);
97
+ if (error) {
98
+ throw new Error(`Validation error: ${error.details[0].message}`);
99
+ }
100
+ return new MaterialCasIdInfo(value.id, value.name, value.casId);
101
+ }
102
+ }
103
+
104
+ export class MaterialEntityDescriptor {
105
+ /**
106
+ * MaterialEntityDescriptor class.
107
+ *
108
+ * @param {string} id - A unique identifier of the material.
109
+ * @param {string} name - The name of the material.
110
+ * @param {string} casId - The CAS ID of the material.
111
+ */
112
+ constructor(
113
+ readonly id: string,
114
+ readonly name: string,
115
+ readonly casId: string
116
+ ) {}
117
+ }
118
+
119
+ export class MaterialEntityDescriptorSchema {
120
+ schema: Joi.ObjectSchema;
121
+
122
+ constructor() {
123
+ this.schema = Joi.object({
124
+ id: Joi.string().guid({ version: "uuidv4" }).required(),
125
+ displayName: Joi.string().required(),
126
+ extendedProperties: Joi.object({
127
+ casId: Joi.string().required(),
128
+ }).required(),
129
+ }).unknown(true);
130
+ }
131
+
132
+ /** Validates and transforms data into a MaterialEntityDescriptor object.
133
+ * @param data - The input data to validate and transform.
134
+ * @returns A MaterialEntityDescriptor instance.
135
+ * @throws Error if validation fails.
136
+ */
137
+ makeMaterialInfo(data: {
138
+ id: string;
139
+ displayName: string;
140
+ extendedProperties: { casId: string };
141
+ }): MaterialEntityDescriptor {
142
+ const { error, value } = this.schema.validate(data);
143
+ if (error) {
144
+ throw new Error(`Validation error: ${error.details[0].message}`);
145
+ }
146
+
147
+ // Add the cas_id to the data dictionary.
148
+ value.cas_id = value.extendedProperties.casId;
149
+
150
+ // Remove the extended_properties from the data dictionary.
151
+ delete value.extendedProperties;
152
+
153
+ // Return a new instance of the MaterialEntityDescriptor class.
154
+ return new MaterialEntityDescriptor(
155
+ value.id,
156
+ value.displayName,
157
+ value.cas_id
158
+ );
159
+ }
160
+ }
161
+
162
+ async function getDataFromUrl<T>(
163
+ url: string,
164
+ schemaClass: SchemaClass,
165
+ many: boolean = false
166
+ ): Promise<T | T[]> {
167
+ try {
168
+ const response = await getRequest(url);
169
+
170
+ if (response.status !== 200) {
171
+ throw new Error(
172
+ `Failed to get data: ${response.status} ${response.statusText}`
173
+ );
174
+ }
175
+
176
+ const data = response.data;
177
+
178
+ // Access the Joi schema from the schema class
179
+ const validationSchema = many
180
+ ? Joi.array().items(schemaClass.schema)
181
+ : schemaClass.schema;
182
+
183
+ // Validate the data
184
+ const { error, value } = validationSchema.validate(data, {
185
+ abortEarly: false,
186
+ });
187
+
188
+ if (error) {
189
+ const errorMessages = error.details
190
+ .map((e: { message: any }) => e.message)
191
+ .join(", ");
192
+ throw new Error(`Error retrieving data: ${errorMessages}`);
193
+ }
194
+
195
+ return value;
196
+ } catch (err: unknown) {
197
+ throw new Error(
198
+ `Error retrieving data: ${
199
+ err instanceof Error ? err.message : "Unknown error"
200
+ }`
201
+ );
202
+ }
203
+ }
204
+
205
+ export async function getAllCasIds(): Promise<MaterialCasIdInfo[]> {
206
+ try {
207
+ // Generate the URL
208
+ const apiTarget = getMaterialsApiTarget();
209
+ const clientAliasId = getClientAliasId();
210
+ const url = `${apiTarget}cas?clientId=${clientAliasId}`;
211
+
212
+ // Fetch and validate the data
213
+ return getDataFromUrl(url, new MaterialCasIdInfoSchema(), true) as Promise<
214
+ MaterialCasIdInfo[]
215
+ >;
216
+ } catch (error: unknown) {
217
+ const errorMessage =
218
+ error instanceof Error ? error.message : "Unknown error";
219
+ throw new Error(`Error retrieving CAS IDs: ${errorMessage}`);
220
+ }
221
+ }
222
+
223
+ export async function getMaterialByCasId(casId: string): Promise<Material> {
224
+ try {
225
+ // Generate the URL
226
+ const apiTarget = getMaterialsApiTarget();
227
+ const clientAliasId = getClientAliasId();
228
+ const url = `${apiTarget}materials/casid=${casId}?clientId=${clientAliasId}`;
229
+
230
+ // Fetch and validate the data
231
+ return getDataFromUrl(url, new MaterialSchema()) as Promise<Material>;
232
+ } catch (error: unknown) {
233
+ const errorMessage =
234
+ error instanceof Error ? error.message : "Unknown error";
235
+ throw new Error(
236
+ `Error retrieving material with CAS ID ${casId}: ${errorMessage}`
237
+ );
238
+ }
239
+ }
240
+
241
+ export async function getComponents(
242
+ source: number
243
+ ): Promise<MaterialComponentData[]> {
244
+ try {
245
+ // Generate the URL
246
+ const apiTarget = getMaterialsApiTarget();
247
+ const clientAliasId = getClientAliasId();
248
+ const url = `${apiTarget}components?clientId=${clientAliasId}&sources=${source}`;
249
+
250
+ // Fetch and validate the data
251
+ return getDataFromUrl(
252
+ url,
253
+ new MaterialEntityDescriptorSchema(),
254
+ true
255
+ ) as Promise<MaterialComponentData[]>;
256
+ } catch (error: unknown) {
257
+ const errorMessage =
258
+ error instanceof Error ? error.message : "Unknown error";
259
+ throw new Error(`Error retrieving components: ${errorMessage}`);
260
+ }
261
+ }
262
+
263
+ export async function getDnvComponents(): Promise<MaterialComponentData[]> {
264
+ return getComponents(1);
265
+ }
266
+
267
+ export async function getDipprComponents(): Promise<MaterialComponentData[]> {
268
+ return getComponents(2);
269
+ }
270
+
271
+ export async function getUserComponents(): Promise<MaterialComponentData[]> {
272
+ return getComponents(3);
273
+ }
274
+
275
+ export async function getComponentById(
276
+ id: string
277
+ ): Promise<MaterialComponentData> {
278
+ try {
279
+ // Generate the URL
280
+ const apiTarget = getMaterialsApiTarget();
281
+ const clientAliasId = getClientAliasId();
282
+ const url = `${apiTarget}components/id=${id}?clientId=${clientAliasId}`;
283
+
284
+ // Fetch and validate the data
285
+ return getDataFromUrl(
286
+ url,
287
+ new MaterialComponentDataSchema()
288
+ ) as Promise<MaterialComponentData>;
289
+ } catch (error: unknown) {
290
+ const errorMessage =
291
+ error instanceof Error ? error.message : "Unknown error";
292
+ throw new Error(
293
+ `Error retrieving component with ID ${id}: ${errorMessage}`
294
+ );
295
+ }
296
+ }
297
+
298
+ export async function getComponentByName(
299
+ name: string
300
+ ): Promise<MaterialComponentData> {
301
+ try {
302
+ // Generate the URL
303
+ const apiTarget = getMaterialsApiTarget();
304
+ const clientAliasId = getClientAliasId();
305
+ const url = `${apiTarget}components/name=${encodeURIComponent(
306
+ name
307
+ )}?clientId=${clientAliasId}`;
308
+
309
+ // Fetch and validate the data
310
+ return getDataFromUrl(
311
+ url,
312
+ new MaterialComponentDataSchema()
313
+ ) as Promise<MaterialComponentData>;
314
+ } catch (error: unknown) {
315
+ const errorMessage =
316
+ error instanceof Error ? error.message : "Unknown error";
317
+ throw new Error(
318
+ `Error retrieving component with name ${name}: ${errorMessage}`
319
+ );
320
+ }
321
+ }
322
+
323
+ export async function getComponentByCasId(casId: string) {
324
+ try {
325
+ // Generate the URL
326
+ const apiTarget = getMaterialsApiTarget();
327
+ const clientAliasId = getClientAliasId();
328
+ const url = `${apiTarget}components/casid=${encodeURIComponent(
329
+ casId
330
+ )}?clientId=${clientAliasId}`;
331
+
332
+ // Fetch and validate the data
333
+ return getDataFromUrl(
334
+ url,
335
+ new MaterialComponentDataSchema()
336
+ ) as Promise<MaterialComponentData>;
337
+ } catch (error: unknown) {
338
+ const errorMessage =
339
+ error instanceof Error ? error.message : "Unknown error";
340
+ throw new Error(
341
+ `Error retrieving component with CAS ID ${casId}: ${errorMessage}`
342
+ );
343
+ }
344
+ }
345
+
346
+ export async function storeDataAndGetResponse<T>(
347
+ url: string,
348
+ data: any,
349
+ schemaClass: SchemaClass
350
+ ): Promise<T> {
351
+ // Serialize the data using the schema
352
+
353
+ const { error, value } = schemaClass.schema.validate(data);
354
+ if (error) {
355
+ throw new Error(`Validation error: ${error.details[0].message}`);
356
+ }
357
+
358
+ const jsonText = JSON.stringify(value);
359
+
360
+ // Send a POST request
361
+ const postResponse = await postRequest(url, jsonText);
362
+
363
+ // Check if the response status is 201 (created)
364
+ if (postResponse.status === 201) {
365
+ const materialUrl = postResponse.headers["location"];
366
+ if (!materialUrl) {
367
+ throw new Error("Failed to store data: no location header in response");
368
+ }
369
+
370
+ // Send a GET request to the material URL
371
+ const getResponse = await getRequest(materialUrl);
372
+
373
+ // Check if the GET request is successful
374
+ if (getResponse.status === 200) {
375
+ // Validate and parse the response data using the schema
376
+ const { error, value } = schemaClass.schema.validate(getResponse.data);
377
+ if (error) {
378
+ throw new Error(`Validation error: ${error.details[0].message}`);
379
+ }
380
+ return value;
381
+ } else {
382
+ throw new Error(
383
+ `Failed to retrieve data: ${getResponse.status} ${getResponse.statusText}`
384
+ );
385
+ }
386
+ } else {
387
+ throw new Error(
388
+ `Failed to store data: ${postResponse.status} ${postResponse.statusText}`
389
+ );
390
+ }
391
+ }
392
+
393
+ export async function storeMaterialComponentData(
394
+ materialComponentData: MaterialComponentData
395
+ ): Promise<MaterialComponentData> {
396
+ try {
397
+ // Generate the URL
398
+ const apiTarget = getMaterialsApiTarget();
399
+ const clientAliasId = getClientAliasId();
400
+ const url = `${apiTarget}components?clientId=${clientAliasId}`;
401
+
402
+ // Store the data and return the response
403
+ return storeDataAndGetResponse(
404
+ url,
405
+ materialComponentData,
406
+ new MaterialComponentDataSchema()
407
+ );
408
+ } catch (error: unknown) {
409
+ const errorMessage =
410
+ error instanceof Error ? error.message : "Unknown error";
411
+ throw new Error(`Error storing material component data: ${errorMessage}`);
412
+ }
413
+ }
414
+
415
+ export async function storeMaterialComponentAndCreateMaterial(
416
+ materialComponentData: MaterialComponentData
417
+ ): Promise<Material> {
418
+ try {
419
+ // Generate the URL
420
+ const apiTarget = getMaterialsApiTarget();
421
+ const clientAliasId = getClientAliasId();
422
+ const url = `${apiTarget}components/material?clientId=${clientAliasId}`;
423
+
424
+ // Store the data and return the response
425
+ return storeDataAndGetResponse(
426
+ url,
427
+ materialComponentData,
428
+ new MaterialSchema()
429
+ );
430
+ } catch (error: unknown) {
431
+ const errorMessage =
432
+ error instanceof Error ? error.message : "Unknown error";
433
+ throw new Error(
434
+ `Error storing material component and creating material: ${errorMessage}`
435
+ );
436
+ }
437
+ }
438
+
439
+ export async function updateMaterialComponent(
440
+ materialComponentData: MaterialComponentData
441
+ ): Promise<boolean> {
442
+ try {
443
+ // Generate the URL
444
+ const apiTarget = getMaterialsApiTarget();
445
+ const clientAliasId = getClientAliasId();
446
+ const url = `${apiTarget}components?clientId=${clientAliasId}`;
447
+
448
+ // Serialize the data
449
+ const jsonText = JSON.stringify(materialComponentData);
450
+
451
+ // Send a PUT request
452
+ const response = await putRequest(url, jsonText);
453
+
454
+ // Check if the response status is 204 (no content)
455
+ if (response.status === 204) {
456
+ return true;
457
+ } else {
458
+ throw new Error(
459
+ `Failed to update material component: ${response.status} ${response.statusText}`
460
+ );
461
+ }
462
+ } catch (error: unknown) {
463
+ const errorMessage =
464
+ error instanceof Error ? error.message : "Unknown error";
465
+ throw new Error(`Error updating material component: ${errorMessage}`);
466
+ }
467
+ }
468
+
469
+ export async function getMaterials(): Promise<Material[]> {
470
+ try {
471
+ // Generate the URL
472
+ const apiTarget = getMaterialsApiTarget();
473
+ const clientAliasId = getClientAliasId();
474
+ const url = `${apiTarget}materials?clientId=${clientAliasId}`;
475
+
476
+ // Fetch and validate the data
477
+ return getDataFromUrl(url, new MaterialSchema(), true) as Promise<
478
+ Material[]
479
+ >;
480
+ } catch (error: unknown) {
481
+ const errorMessage =
482
+ error instanceof Error ? error.message : "Unknown error";
483
+ throw new Error(`Error retrieving materials: ${errorMessage}`);
484
+ }
485
+ }
486
+
487
+ export async function getMaterialById(id: string): Promise<Material> {
488
+ try {
489
+ // Generate the URL
490
+ const apiTarget = getMaterialsApiTarget();
491
+ const clientAliasId = getClientAliasId();
492
+ const url = `${apiTarget}materials/id=${id}?clientId=${clientAliasId}`;
493
+
494
+ // Fetch and validate the data
495
+ return getDataFromUrl(url, new MaterialSchema()) as Promise<Material>;
496
+ } catch (error: unknown) {
497
+ const errorMessage =
498
+ error instanceof Error ? error.message : "Unknown error";
499
+ throw new Error(`Error retrieving material with ID ${id}: ${errorMessage}`);
500
+ }
501
+ }
502
+
503
+ export async function getMaterialByName(name: string): Promise<Material> {
504
+ try {
505
+ // Generate the URL
506
+ const apiTarget = getMaterialsApiTarget();
507
+ const clientAliasId = getClientAliasId();
508
+ const url = `${apiTarget}materials/name=${name}?clientId=${clientAliasId}`;
509
+
510
+ // Fetch and validate the data
511
+ return getDataFromUrl(url, new MaterialSchema()) as Promise<Material>;
512
+ } catch (error: unknown) {
513
+ const errorMessage =
514
+ error instanceof Error ? error.message : "Unknown error";
515
+ throw new Error(
516
+ `Error retrieving material with name ${name}: ${errorMessage}`
517
+ );
518
+ }
519
+ }
520
+
521
+ export async function getMaterialNames() {
522
+ try {
523
+ // Generate the URL
524
+ const apiTarget = getMaterialsApiTarget();
525
+ const clientAliasId = getClientAliasId();
526
+ const url = `${apiTarget}materials/descriptors?clientId=${clientAliasId}`;
527
+
528
+ // Fetch and validate the data
529
+ return getDataFromUrl(url, new MaterialInfoSchema(), true) as Promise<
530
+ MaterialInfo[]
531
+ >;
532
+ } catch (error: unknown) {
533
+ const errorMessage =
534
+ error instanceof Error ? error.message : "Unknown error";
535
+ throw new Error(`Error retrieving material names: ${errorMessage}`);
536
+ }
537
+ }