@jd-data-limited/easy-fm 0.0.12 → 1.0.1-alpha1

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