@jd-data-limited/easy-fm 0.0.7 → 0.0.9

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.
package/index.js CHANGED
@@ -1,503 +1,502 @@
1
- /*
2
- * Copyright (c) 2022. See LICENSE file for more information
3
- */
4
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6
- return new (P || (P = Promise))(function (resolve, reject) {
7
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10
- step((generator = generator.apply(thisArg, _arguments || [])).next());
11
- });
12
- };
13
- // const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
14
- import fetch, { File, FormData } from 'node-fetch';
15
- import { EventEmitter } from "events";
16
- // @ts-ignore
17
- import fs from "fs";
18
- // @ts-ignore
19
- import path from "path";
20
- // @ts-ignore
21
- import { fileURLToPath } from "url";
22
- import * as https from "https";
23
- // import * as btoa from "btoa";
24
- // @ts-ignore
25
- const errs = JSON.parse(fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), 'fmErrors.json')).toString());
26
- export default class FileMakerConnection {
27
- constructor() {
28
- }
29
- get endpoint() {
30
- return `https://${this.hostname}/fmi/data/v2/databases/${encodeURI(this.database)}`;
31
- }
32
- login(hostname, database, username, password, rejectUnauthorized = true) {
33
- return __awaiter(this, void 0, void 0, function* () {
34
- if (this.token)
35
- throw new Error("Already logged in. Run logout() first");
36
- this.username = username;
37
- this.password = password;
38
- this.hostname = hostname;
39
- this.database = database;
40
- this.rejectUnauthroized = rejectUnauthorized;
41
- return yield this.createSession();
42
- });
43
- }
44
- logout() {
45
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
46
- if (!this.token)
47
- reject(new Error("Not logged in"));
48
- let _fetch = yield fetch(`${this.endpoint}/sessions/${this.token}`, {
49
- method: "DELETE",
50
- headers: {
51
- "content-type": "application/json"
52
- }
53
- });
54
- let data = yield _fetch.json();
55
- // console.log(data)
56
- this.token = null;
57
- this.database = null;
58
- this.hostname = null;
59
- resolve();
60
- }));
61
- }
62
- importSession(hostname, database, token, rejectUnauthorized = true) {
63
- this.token = token;
64
- this.database = database;
65
- this.hostname = hostname;
66
- this.rejectUnauthroized = rejectUnauthorized;
67
- }
68
- createSession() {
69
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
70
- fetch(`${this.endpoint}/sessions`, {
71
- hostname: this.hostname,
72
- port: 443,
73
- method: "POST",
74
- headers: {
75
- "Content-Type": "application/json",
76
- "Authorization": "Basic " + Buffer.from(this.username + ":" + this.password).toString("base64")
77
- }
78
- }).then(res => {
79
- console.log(res);
80
- return res.json();
81
- })
82
- .then(res => {
83
- let _res = res;
84
- if (_res.messages[0].code === "0") {
85
- this.token = _res.response.token;
86
- console.log(_res);
87
- resolve(this.token);
88
- }
89
- else {
90
- reject(new FMError(_res.messages[0].code, _res.status, res));
91
- }
92
- })
93
- .catch(e => {
94
- reject(e);
95
- });
96
- }));
97
- }
98
- getLayout(name) {
99
- return new layout(this, name);
100
- }
101
- apiRequest(url, options = {}) {
102
- return __awaiter(this, void 0, void 0, function* () {
103
- if (!options.headers)
104
- options.headers = {};
105
- options.headers["content-type"] = options.headers["content-type"] ? options.headers["content-type"] : "application/json";
106
- options.headers["authorization"] = "Bearer " + this.token;
107
- options.rejectUnauthorized = this.rejectUnauthroized;
108
- let _fetch = yield fetch(url, options);
109
- let data = yield _fetch.json();
110
- return data;
111
- });
112
- }
113
- setGlobals(globalFields) {
114
- // console.log({globalFields})
115
- return new Promise((resolve, reject) => {
116
- this.apiRequest(`${this.endpoint}/globals`, {
117
- method: "PATCH",
118
- body: JSON.stringify({ globalFields })
119
- }).then(res => {
120
- // console.log(res)
121
- if (res.messages[0].code === "0") {
122
- resolve();
123
- }
124
- else {
125
- reject(new FMError(res.messages[0].code, res.status, res));
126
- }
127
- })
128
- .catch(e => {
129
- reject(e);
130
- });
131
- });
132
- }
133
- script(name, parameter) {
134
- return { name, parameter };
135
- }
136
- }
137
- class layout {
138
- constructor(conn, name) {
139
- this.conn = conn;
140
- this.name = name;
141
- }
142
- get endpoint() {
143
- return `${this.conn.endpoint}/layouts/${this.name}`;
144
- }
145
- getScript(script) {
146
- return new script(this, script);
147
- }
148
- createRecord() {
149
- return new Promise((resolve, reject) => {
150
- // Get the layout's metadata
151
- this.conn.apiRequest(`${this.endpoint}`).then(res => {
152
- let fields = {};
153
- for (let _field of res.response.fieldMetaData) {
154
- fields[_field.name] = "";
155
- }
156
- resolve(new record(this, -1, 0, fields));
157
- });
158
- });
159
- }
160
- getRecord(recordId) {
161
- return new record(this, recordId);
162
- }
163
- newFind() {
164
- return new find(this);
165
- }
166
- runScript(script) {
167
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
168
- let url = `${this.endpoint}/script/${encodeURI(script.name)}`;
169
- if (script.parameter)
170
- url += "?" + encodeURI(script.parameter);
171
- this.conn.apiRequest(url, {
172
- port: 443,
173
- method: "GET"
174
- })
175
- .then(res => {
176
- if (res.messages[0].code === "0") {
177
- resolve(res.response);
178
- }
179
- else {
180
- // console.log(res)
181
- reject(new FMError(res.messages[0].code, res.status, res));
182
- }
183
- })
184
- .catch(e => {
185
- reject(e);
186
- });
187
- }));
188
- }
189
- getLayoutMeta() {
190
- return new Promise((resolve, reject) => {
191
- this.conn.apiRequest(this.endpoint).then(res => {
192
- this.metadata = res.response;
193
- resolve(this);
194
- })
195
- .catch(e => reject(e));
196
- });
197
- }
198
- }
199
- class record extends EventEmitter {
200
- constructor(layout, recordId, modId = recordId, fieldData = {}, portalData = null) {
201
- super();
202
- this.layout = layout;
203
- this.recordId = recordId;
204
- this.modId = modId;
205
- this.fields = this.processFieldData(fieldData);
206
- this.portals = [];
207
- if (portalData) {
208
- this.processPortalData(portalData);
209
- }
210
- this.on("saved", () => {
211
- for (let field of this.fields)
212
- field.edited = false;
213
- });
214
- }
215
- get endpoint() {
216
- return `${this.layout.endpoint}/records/${this.recordId}`;
217
- }
218
- get edited() {
219
- return !!this.fields.find(i => i.edited);
220
- }
221
- processPortalData(portalData) {
222
- for (let item of Object.keys(portalData)) {
223
- this.portals.push(new portal(this, item, portalData[item].map(item => {
224
- let fieldData = item;
225
- delete fieldData.recordId;
226
- delete fieldData.modId;
227
- return new portalItem(this, item.recordId, item.modId, fieldData);
228
- })));
229
- }
230
- }
231
- processFieldData(fieldData) {
232
- return Object.keys(fieldData).map(item => {
233
- return new field(this, item, fieldData[item]);
234
- });
235
- }
236
- get() {
237
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
238
- if (!this.layout.metadata)
239
- yield this.layout.getLayoutMeta();
240
- this.layout.conn.apiRequest(this.endpoint, {
241
- port: 443,
242
- method: "GET"
243
- })
244
- .then(res => {
245
- if (res.messages[0].code === "0") {
246
- // console.log(res, res.response.data)
247
- this.modId = res.response.data[0].modId;
248
- this.fields = this.processFieldData(res.response.data[0].fieldData);
249
- this.portalData = [];
250
- if (res.response.data[0].portalData)
251
- this.processPortalData(res.response.data[0].portalData);
252
- resolve(this);
253
- }
254
- else {
255
- reject(new FMError(res.messages[0].code, res.status, res));
256
- }
257
- })
258
- .catch(e => {
259
- reject(e);
260
- });
261
- }));
262
- }
263
- commit(extraBody = {}) {
264
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
265
- let data = this.toObject();
266
- delete data.recordId;
267
- delete data.modId;
268
- if (this.recordId === -1) {
269
- // This is a new record
270
- this.layout.conn.apiRequest(`${this.layout.endpoint}/records`, {
271
- port: 443,
272
- method: "POST",
273
- body: JSON.stringify({
274
- fieldData: data.fieldData
275
- })
276
- })
277
- .then(res => {
278
- if (res.messages[0].code === "0") {
279
- this.recordId = res.response.recordId;
280
- this.modId = res.response.modId;
281
- resolve(this);
282
- }
283
- else {
284
- reject(new FMError(res.messages[0].code, res.status, res));
285
- }
286
- })
287
- .catch(e => {
288
- reject(e);
289
- });
290
- return;
291
- }
292
- for (let item of Object.keys(extraBody))
293
- data[item] = extraBody[item];
294
- this.layout.conn.apiRequest(this.endpoint, {
295
- port: 443,
296
- method: "PATCH",
297
- body: JSON.stringify(data)
298
- })
299
- .then(res => {
300
- if (res.messages[0].code === "0") {
301
- this.modId = res.response.modId;
302
- this.emit("saved");
303
- resolve(this);
304
- }
305
- else {
306
- reject(new FMError(res.messages[0].code, res.status, res));
307
- }
308
- })
309
- .catch(e => {
310
- reject(e);
311
- });
312
- }));
313
- }
314
- getField(field) {
315
- return this.fields.find(_field => _field.id === field);
316
- }
317
- getPortal(portal) {
318
- return this.portals.find(p => p.name === portal);
319
- }
320
- toObject(filter = (a) => a.edited, portalFilter = (a) => a.records.find(record => record.edited), portalRowFilter = (a) => a.edited, portalFieldFilter = (a) => a.edited) {
321
- let fields_processed = {};
322
- for (let field of this.fields.filter(field => filter(field))) {
323
- fields_processed[field.id] = field.value;
324
- }
325
- let obj = {
326
- "recordId": this.recordId,
327
- "modId": this.modId,
328
- "fieldData": fields_processed
329
- };
330
- // Check if there's been any edited portal information
331
- let portals = this.portals.filter(a => portalFilter(a));
332
- if (portals) {
333
- obj["portalData"] = {};
334
- for (let portal of portals) {
335
- obj["portalData"][portal.name] = portal.records.filter(a => portalRowFilter(a)).map(record => {
336
- return record.toObject(portalFieldFilter);
337
- });
338
- }
339
- }
340
- return obj;
341
- }
342
- }
343
- class field {
344
- constructor(record, id, contents) {
345
- this.record = record;
346
- this.id = id;
347
- this.value = contents;
348
- this.edited = false;
349
- }
350
- set(content) {
351
- if (this.dataType === "container")
352
- throw "Cannot set container value using set(). Use upload() instead.";
353
- this.value = content;
354
- this.edited = true;
355
- }
356
- get dataType() {
357
- if (!this.record.layout.metadata)
358
- return "unknown";
359
- if (this.record instanceof portalItem) {
360
- return this.record.layout.metadata.portalMetaData.find(i => i.name === this.id).result || "unknown";
361
- }
362
- else {
363
- return this.record.layout.metadata.fieldMetaData.find(i => i.name === this.id).result || "unknown";
364
- }
365
- }
366
- upload(buffer, filename, mime) {
367
- if (this.dataType !== "container")
368
- throw "Cannot upload a file to the field; " + this.id + " (not a container field)";
369
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
370
- let form = new FormData();
371
- form.append("upload", new File([buffer], filename, { type: mime }));
372
- let _fetch = yield fetch(`${this.record.endpoint}/containers/${this.id}/1`, {
373
- method: "POST",
374
- headers: { "Authorization": "Bearer " + this.record.layout.conn.token },
375
- body: form
376
- }).then(res => res.json())
377
- .then(data => {
378
- let _res = data;
379
- if (_res.messages[0].code === "0") {
380
- resolve();
381
- }
382
- else {
383
- reject(new FMError(_res.messages[0].code, _res.status, data));
384
- }
385
- })
386
- .catch(e => { reject(e); });
387
- }));
388
- }
389
- download() {
390
- return new Promise((resolve, reject) => {
391
- https.get(this.value.toString(), (res) => {
392
- resolve(res);
393
- });
394
- });
395
- }
396
- }
397
- class portal {
398
- constructor(record, name, records = []) {
399
- this.record = record;
400
- this.name = name;
401
- this.records = records;
402
- for (let item of this.records)
403
- item.attachPortal(this);
404
- }
405
- }
406
- class portalItem extends record {
407
- constructor(record, recordId, modId = recordId, fieldData = {}) {
408
- super(record.layout, recordId, modId, fieldData);
409
- record.on("saved", () => {
410
- this.emit("saved");
411
- });
412
- }
413
- attachPortal(portal) {
414
- this.portal = portal;
415
- }
416
- commit(extraBody = {}) {
417
- return this.portal.record.commit(extraBody);
418
- }
419
- toObject(fieldFilter) {
420
- super.toObject();
421
- let res = {
422
- recordId: this.recordId, modId: this.modId
423
- };
424
- for (let field of this.fields.filter(a => fieldFilter(a)))
425
- res[field.id] = field.value;
426
- // console.log(res)
427
- return res;
428
- }
429
- }
430
- class find {
431
- constructor(layout) {
432
- this.layout = layout;
433
- this.queries = [];
434
- this.scripts = {
435
- "script": null,
436
- "script.prerequeset": null,
437
- "script.presort": null // Runs before the sort
438
- };
439
- this.sort = [];
440
- }
441
- toObject() {
442
- let out = { query: this.queries, sort: undefined };
443
- if (this.sort.length !== 0)
444
- out.sort = this.sort;
445
- for (let item of Object.keys(this.scripts)) {
446
- if (this.scripts[item]) {
447
- out[item] = this.scripts[item].name;
448
- if (this.scripts[item].parameter)
449
- out[item + ".param"] = this.scripts[item].parameter;
450
- }
451
- }
452
- return out;
453
- }
454
- addRequests(...requests) {
455
- for (let item of requests)
456
- this.queries.push(item);
457
- return this;
458
- }
459
- addSort(fieldName, sortOrder) {
460
- this.sort.push({ fieldName, sortOrder });
461
- return this;
462
- }
463
- find() {
464
- return new Promise((resolve, reject) => {
465
- // console.log(this.#toObject())
466
- this.layout.conn.apiRequest(`${this.layout.endpoint}/_find`, {
467
- port: 443,
468
- method: "POST",
469
- body: JSON.stringify(this.toObject())
470
- }).then((res) => __awaiter(this, void 0, void 0, function* () {
471
- // // console.log(res)
472
- if (res.messages[0].code === "0") {
473
- // console.log("RESOLVING")
474
- if (!this.layout.metadata)
475
- yield this.layout.getLayoutMeta();
476
- let data = res.response.data.map(item => {
477
- return new record(this.layout, item.recordId, item.modId, item.fieldData, item.portalData);
478
- });
479
- resolve(data);
480
- }
481
- else {
482
- reject(new FMError(res.messages[0].code, res.status, res));
483
- }
484
- }))
485
- .catch(e => {
486
- reject(e);
487
- });
488
- });
489
- }
490
- }
491
- export class FMError extends Error {
492
- constructor(code, httpStatus, res) {
493
- super(code);
494
- this.httpStatus = httpStatus;
495
- this.res = res;
496
- this.code = typeof code === "string" ? parseInt(code) : code;
497
- this.message = errs.find(err => err.e === this.code) || "Unknown error";
498
- }
499
- }
500
- //
501
- // module.exports = {
502
- // default: {FileMakerConnection}
503
- // }
1
+ /*
2
+ * Copyright (c) 2022. See LICENSE file for more information
3
+ */
4
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6
+ return new (P || (P = Promise))(function (resolve, reject) {
7
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
11
+ });
12
+ };
13
+ // const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
14
+ import fetch, { File, FormData } from 'node-fetch';
15
+ import { EventEmitter } from "events";
16
+ // @ts-ignore
17
+ import fs from "fs";
18
+ // @ts-ignore
19
+ import path from "path";
20
+ // @ts-ignore
21
+ import { fileURLToPath } from "url";
22
+ import * as https from "https";
23
+ // import * as btoa from "btoa";
24
+ // @ts-ignore
25
+ const errs = JSON.parse(fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), 'fmErrors.json')).toString());
26
+ export default class FileMakerConnection {
27
+ constructor() { }
28
+ get endpoint() {
29
+ return `https://${this.hostname}/fmi/data/v2/databases/${encodeURI(this.database)}`;
30
+ }
31
+ login(hostname, database, username, password, rejectUnauthorized = true) {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ if (this.token)
34
+ throw new Error("Already logged in. Run logout() first");
35
+ this.username = username;
36
+ this.password = password;
37
+ this.hostname = hostname;
38
+ this.database = database;
39
+ this.rejectUnauthroized = rejectUnauthorized;
40
+ return yield this.createSession();
41
+ });
42
+ }
43
+ logout() {
44
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
45
+ if (!this.token)
46
+ reject(new Error("Not logged in"));
47
+ let _fetch = yield fetch(`${this.endpoint}/sessions/${this.token}`, {
48
+ method: "DELETE",
49
+ headers: {
50
+ "content-type": "application/json"
51
+ }
52
+ });
53
+ let data = yield _fetch.json();
54
+ // console.log(data)
55
+ this.token = null;
56
+ this.database = null;
57
+ this.hostname = null;
58
+ resolve();
59
+ }));
60
+ }
61
+ importSession(hostname, database, token, rejectUnauthorized = true) {
62
+ this.token = token;
63
+ this.database = database;
64
+ this.hostname = hostname;
65
+ this.rejectUnauthroized = rejectUnauthorized;
66
+ }
67
+ createSession() {
68
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
69
+ fetch(`${this.endpoint}/sessions`, {
70
+ hostname: this.hostname,
71
+ port: 443,
72
+ method: "POST",
73
+ headers: {
74
+ "Content-Type": "application/json",
75
+ "Authorization": "Basic " + Buffer.from(this.username + ":" + this.password).toString("base64")
76
+ }
77
+ }).then(res => {
78
+ console.log(res);
79
+ return res.json();
80
+ })
81
+ .then(res => {
82
+ let _res = res;
83
+ if (_res.messages[0].code === "0") {
84
+ this.token = _res.response.token;
85
+ console.log(_res);
86
+ resolve(this.token);
87
+ }
88
+ else {
89
+ reject(new FMError(_res.messages[0].code, _res.status, res));
90
+ }
91
+ })
92
+ .catch(e => {
93
+ reject(e);
94
+ });
95
+ }));
96
+ }
97
+ getLayout(name) {
98
+ return new layout(this, name);
99
+ }
100
+ apiRequest(url, options = {}) {
101
+ return __awaiter(this, void 0, void 0, function* () {
102
+ if (!options.headers)
103
+ options.headers = {};
104
+ options.headers["content-type"] = options.headers["content-type"] ? options.headers["content-type"] : "application/json";
105
+ options.headers["authorization"] = "Bearer " + this.token;
106
+ options.rejectUnauthorized = this.rejectUnauthroized;
107
+ let _fetch = yield fetch(url, options);
108
+ let data = yield _fetch.json();
109
+ return data;
110
+ });
111
+ }
112
+ setGlobals(globalFields) {
113
+ // console.log({globalFields})
114
+ return new Promise((resolve, reject) => {
115
+ this.apiRequest(`${this.endpoint}/globals`, {
116
+ method: "PATCH",
117
+ body: JSON.stringify({ globalFields })
118
+ }).then(res => {
119
+ // console.log(res)
120
+ if (res.messages[0].code === "0") {
121
+ resolve();
122
+ }
123
+ else {
124
+ reject(new FMError(res.messages[0].code, res.status, res));
125
+ }
126
+ })
127
+ .catch(e => {
128
+ reject(e);
129
+ });
130
+ });
131
+ }
132
+ script(name, parameter) {
133
+ return { name, parameter };
134
+ }
135
+ }
136
+ class layout {
137
+ constructor(conn, name) {
138
+ this.conn = conn;
139
+ this.name = name;
140
+ }
141
+ get endpoint() {
142
+ return `${this.conn.endpoint}/layouts/${this.name}`;
143
+ }
144
+ getScript(script) {
145
+ return new script(this, script);
146
+ }
147
+ createRecord() {
148
+ return new Promise((resolve, reject) => {
149
+ // Get the layout's metadata
150
+ this.conn.apiRequest(`${this.endpoint}`).then(res => {
151
+ let fields = {};
152
+ for (let _field of res.response.fieldMetaData) {
153
+ fields[_field.name] = "";
154
+ }
155
+ resolve(new record(this, -1, 0, fields));
156
+ });
157
+ });
158
+ }
159
+ getRecord(recordId) {
160
+ return new record(this, recordId);
161
+ }
162
+ newFind() {
163
+ return new find(this);
164
+ }
165
+ runScript(script) {
166
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
167
+ let url = `${this.endpoint}/script/${encodeURI(script.name)}`;
168
+ if (script.parameter)
169
+ url += "?" + encodeURI(script.parameter);
170
+ this.conn.apiRequest(url, {
171
+ port: 443,
172
+ method: "GET"
173
+ })
174
+ .then(res => {
175
+ if (res.messages[0].code === "0") {
176
+ resolve(res.response);
177
+ }
178
+ else {
179
+ // console.log(res)
180
+ reject(new FMError(res.messages[0].code, res.status, res));
181
+ }
182
+ })
183
+ .catch(e => {
184
+ reject(e);
185
+ });
186
+ }));
187
+ }
188
+ getLayoutMeta() {
189
+ return new Promise((resolve, reject) => {
190
+ this.conn.apiRequest(this.endpoint).then(res => {
191
+ this.metadata = res.response;
192
+ resolve(this);
193
+ })
194
+ .catch(e => reject(e));
195
+ });
196
+ }
197
+ }
198
+ class record extends EventEmitter {
199
+ constructor(layout, recordId, modId = recordId, fieldData = {}, portalData = null) {
200
+ super();
201
+ this.layout = layout;
202
+ this.recordId = recordId;
203
+ this.modId = modId;
204
+ this.fields = this.processFieldData(fieldData);
205
+ this.portals = [];
206
+ if (portalData) {
207
+ this.processPortalData(portalData);
208
+ }
209
+ this.on("saved", () => {
210
+ for (let field of this.fields)
211
+ field.edited = false;
212
+ });
213
+ }
214
+ get endpoint() {
215
+ return `${this.layout.endpoint}/records/${this.recordId}`;
216
+ }
217
+ get edited() {
218
+ return !!this.fields.find(i => i.edited);
219
+ }
220
+ processPortalData(portalData) {
221
+ for (let item of Object.keys(portalData)) {
222
+ this.portals.push(new portal(this, item, portalData[item].map(item => {
223
+ let fieldData = item;
224
+ delete fieldData.recordId;
225
+ delete fieldData.modId;
226
+ return new portalItem(this, item.recordId, item.modId, fieldData);
227
+ })));
228
+ }
229
+ }
230
+ processFieldData(fieldData) {
231
+ return Object.keys(fieldData).map(item => {
232
+ return new field(this, item, fieldData[item]);
233
+ });
234
+ }
235
+ get() {
236
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
237
+ if (!this.layout.metadata)
238
+ yield this.layout.getLayoutMeta();
239
+ this.layout.conn.apiRequest(this.endpoint, {
240
+ port: 443,
241
+ method: "GET"
242
+ })
243
+ .then(res => {
244
+ if (res.messages[0].code === "0") {
245
+ // console.log(res, res.response.data)
246
+ this.modId = res.response.data[0].modId;
247
+ this.fields = this.processFieldData(res.response.data[0].fieldData);
248
+ this.portalData = [];
249
+ if (res.response.data[0].portalData)
250
+ this.processPortalData(res.response.data[0].portalData);
251
+ resolve(this);
252
+ }
253
+ else {
254
+ reject(new FMError(res.messages[0].code, res.status, res));
255
+ }
256
+ })
257
+ .catch(e => {
258
+ reject(e);
259
+ });
260
+ }));
261
+ }
262
+ commit(extraBody = {}) {
263
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
264
+ let data = this.toObject();
265
+ delete data.recordId;
266
+ delete data.modId;
267
+ if (this.recordId === -1) {
268
+ // This is a new record
269
+ this.layout.conn.apiRequest(`${this.layout.endpoint}/records`, {
270
+ port: 443,
271
+ method: "POST",
272
+ body: JSON.stringify({
273
+ fieldData: data.fieldData
274
+ })
275
+ })
276
+ .then(res => {
277
+ if (res.messages[0].code === "0") {
278
+ this.recordId = res.response.recordId;
279
+ this.modId = res.response.modId;
280
+ resolve(this);
281
+ }
282
+ else {
283
+ reject(new FMError(res.messages[0].code, res.status, res));
284
+ }
285
+ })
286
+ .catch(e => {
287
+ reject(e);
288
+ });
289
+ return;
290
+ }
291
+ for (let item of Object.keys(extraBody))
292
+ data[item] = extraBody[item];
293
+ this.layout.conn.apiRequest(this.endpoint, {
294
+ port: 443,
295
+ method: "PATCH",
296
+ body: JSON.stringify(data)
297
+ })
298
+ .then(res => {
299
+ if (res.messages[0].code === "0") {
300
+ this.modId = res.response.modId;
301
+ this.emit("saved");
302
+ resolve(this);
303
+ }
304
+ else {
305
+ reject(new FMError(res.messages[0].code, res.status, res));
306
+ }
307
+ })
308
+ .catch(e => {
309
+ reject(e);
310
+ });
311
+ }));
312
+ }
313
+ getField(field) {
314
+ return this.fields.find(_field => _field.id === field);
315
+ }
316
+ getPortal(portal) {
317
+ return this.portals.find(p => p.name === portal);
318
+ }
319
+ toObject(filter = (a) => a.edited, portalFilter = (a) => a.records.find(record => record.edited), portalRowFilter = (a) => a.edited, portalFieldFilter = (a) => a.edited) {
320
+ let fields_processed = {};
321
+ for (let field of this.fields.filter(field => filter(field))) {
322
+ fields_processed[field.id] = field.value;
323
+ }
324
+ let obj = {
325
+ "recordId": this.recordId,
326
+ "modId": this.modId,
327
+ "fieldData": fields_processed
328
+ };
329
+ // Check if there's been any edited portal information
330
+ let portals = this.portals.filter(a => portalFilter(a));
331
+ if (portals) {
332
+ obj["portalData"] = {};
333
+ for (let portal of portals) {
334
+ obj["portalData"][portal.name] = portal.records.filter(a => portalRowFilter(a)).map(record => {
335
+ return record.toObject(portalFieldFilter);
336
+ });
337
+ }
338
+ }
339
+ return obj;
340
+ }
341
+ }
342
+ class field {
343
+ constructor(record, id, contents) {
344
+ this.record = record;
345
+ this.id = id;
346
+ this.value = contents;
347
+ this.edited = false;
348
+ }
349
+ set(content) {
350
+ if (this.dataType === "container")
351
+ throw "Cannot set container value using set(). Use upload() instead.";
352
+ this.value = content;
353
+ this.edited = true;
354
+ }
355
+ get dataType() {
356
+ if (!this.record.layout.metadata)
357
+ return "unknown";
358
+ if (this.record instanceof portalItem) {
359
+ return this.record.layout.metadata.portalMetaData.find(i => i.name === this.id).result || "unknown";
360
+ }
361
+ else {
362
+ return this.record.layout.metadata.fieldMetaData.find(i => i.name === this.id).result || "unknown";
363
+ }
364
+ }
365
+ upload(buffer, filename, mime) {
366
+ if (this.dataType !== "container")
367
+ throw "Cannot upload a file to the field; " + this.id + " (not a container field)";
368
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
369
+ let form = new FormData();
370
+ form.append("upload", new File([buffer], filename, { type: mime }));
371
+ let _fetch = yield fetch(`${this.record.endpoint}/containers/${this.id}/1`, {
372
+ method: "POST",
373
+ headers: { "Authorization": "Bearer " + this.record.layout.conn.token },
374
+ body: form
375
+ }).then(res => res.json())
376
+ .then(data => {
377
+ let _res = data;
378
+ if (_res.messages[0].code === "0") {
379
+ resolve();
380
+ }
381
+ else {
382
+ reject(new FMError(_res.messages[0].code, _res.status, data));
383
+ }
384
+ })
385
+ .catch(e => { reject(e); });
386
+ }));
387
+ }
388
+ download() {
389
+ return new Promise((resolve, reject) => {
390
+ https.get(this.value.toString(), (res) => {
391
+ resolve(res);
392
+ });
393
+ });
394
+ }
395
+ }
396
+ class portal {
397
+ constructor(record, name, records = []) {
398
+ this.record = record;
399
+ this.name = name;
400
+ this.records = records;
401
+ for (let item of this.records)
402
+ item.attachPortal(this);
403
+ }
404
+ }
405
+ class portalItem extends record {
406
+ constructor(record, recordId, modId = recordId, fieldData = {}) {
407
+ super(record.layout, recordId, modId, fieldData);
408
+ record.on("saved", () => {
409
+ this.emit("saved");
410
+ });
411
+ }
412
+ attachPortal(portal) {
413
+ this.portal = portal;
414
+ }
415
+ commit(extraBody = {}) {
416
+ return this.portal.record.commit(extraBody);
417
+ }
418
+ toObject(fieldFilter) {
419
+ super.toObject();
420
+ let res = {
421
+ recordId: this.recordId, modId: this.modId
422
+ };
423
+ for (let field of this.fields.filter(a => fieldFilter(a)))
424
+ res[field.id] = field.value;
425
+ // console.log(res)
426
+ return res;
427
+ }
428
+ }
429
+ class find {
430
+ constructor(layout) {
431
+ this.layout = layout;
432
+ this.queries = [];
433
+ this.scripts = {
434
+ "script": null,
435
+ "script.prerequeset": null,
436
+ "script.presort": null // Runs before the sort
437
+ };
438
+ this.sort = [];
439
+ }
440
+ toObject() {
441
+ let out = { query: this.queries, sort: undefined };
442
+ if (this.sort.length !== 0)
443
+ out.sort = this.sort;
444
+ for (let item of Object.keys(this.scripts)) {
445
+ if (this.scripts[item]) {
446
+ out[item] = this.scripts[item].name;
447
+ if (this.scripts[item].parameter)
448
+ out[item + ".param"] = this.scripts[item].parameter;
449
+ }
450
+ }
451
+ return out;
452
+ }
453
+ addRequests(...requests) {
454
+ for (let item of requests)
455
+ this.queries.push(item);
456
+ return this;
457
+ }
458
+ addSort(fieldName, sortOrder) {
459
+ this.sort.push({ fieldName, sortOrder });
460
+ return this;
461
+ }
462
+ find() {
463
+ return new Promise((resolve, reject) => {
464
+ // console.log(this.#toObject())
465
+ this.layout.conn.apiRequest(`${this.layout.endpoint}/_find`, {
466
+ port: 443,
467
+ method: "POST",
468
+ body: JSON.stringify(this.toObject())
469
+ }).then((res) => __awaiter(this, void 0, void 0, function* () {
470
+ // // console.log(res)
471
+ if (res.messages[0].code === "0") {
472
+ // console.log("RESOLVING")
473
+ if (!this.layout.metadata)
474
+ yield this.layout.getLayoutMeta();
475
+ let data = res.response.data.map(item => {
476
+ return new record(this.layout, item.recordId, item.modId, item.fieldData, item.portalData);
477
+ });
478
+ resolve(data);
479
+ }
480
+ else {
481
+ reject(new FMError(res.messages[0].code, res.status, res));
482
+ }
483
+ }))
484
+ .catch(e => {
485
+ reject(e);
486
+ });
487
+ });
488
+ }
489
+ }
490
+ export class FMError extends Error {
491
+ constructor(code, httpStatus, res) {
492
+ super(errs.find(err => err.e === this.code) || "Unknown error");
493
+ this.httpStatus = httpStatus;
494
+ this.res = res;
495
+ this.code = typeof code === "string" ? parseInt(code) : code;
496
+ Error.captureStackTrace(this, FMError);
497
+ }
498
+ }
499
+ //
500
+ // module.exports = {
501
+ // default: {FileMakerConnection}
502
+ // }