From dba378ea88818194c16f5f0caf55b761c5ccfb1b Mon Sep 17 00:00:00 2001
From: Volker Schukai <volker.schukai@schukai.com>
Date: Sun, 15 Jan 2023 18:33:56 +0100
Subject: [PATCH] fix: error in the status processing

---
 .../source/data/datasource/server/restapi.mjs | 111 +++++++-----------
 .../cases/data/datasource/server/restapi.mjs  |  23 ++--
 2 files changed, 57 insertions(+), 77 deletions(-)

diff --git a/application/source/data/datasource/server/restapi.mjs b/application/source/data/datasource/server/restapi.mjs
index 4d7065cec..191a29f14 100644
--- a/application/source/data/datasource/server/restapi.mjs
+++ b/application/source/data/datasource/server/restapi.mjs
@@ -114,44 +114,17 @@ class RestAPI extends Server {
      * @throws {Error} the data cannot be read
      */
     read() {
+
         const self = this;
-        let response;
 
         let init = self.getOption('read.init');
         if (!isObject(init)) init = {};
+        if (!init['method']) init['method'] = 'GET';
 
-        return new Promise((resolve, reject) => {
-            fetch(self.getOption('read.url'), init).then(resp => {
-                response = resp;
-
-                const acceptedStatus = self.getOption('read.acceptedStatus', [200]);
-
-                if (acceptedStatus.indexOf(resp.status) === -1) {
-                    throw Error('the data cannot be read (response ' + resp.status + ')')
-                }
-
-                return resp.text()
-            }).then(body => {
-
-                let obj;
-
-                try {
-                    obj = JSON.parse(body);
-
-                } catch (e) {
-
-                    if (body.length > 100) {
-                        body = body.substring(0, 97) + '...';
-                    }
-
-                    throw new Error('the response does not contain a valid json (actual: ' + body + ').');
-                }
-
-                self.set(self.transformServerPayload.call(self, obj));
-                resolve(response);
-            }).catch(reject);
+        return fetchData.call(this, 'read', (obj) => {
+            self.set(self.transformServerPayload.call(self, obj));
+        });
 
-        })
     }
 
     /**
@@ -159,6 +132,7 @@ class RestAPI extends Server {
      * @throws {WriteError} the data cannot be written
      */
     write() {
+
         const self = this;
 
         let init = self.getOption('write.init');
@@ -168,60 +142,65 @@ class RestAPI extends Server {
                 'Content-Type': 'application/json'
             }
         }
+        if (!init['method']) init['method'] = 'POST';
 
         let obj = self.prepareServerPayload(self.get());
         init['body'] = JSON.stringify(obj);
 
-        return new Promise((resolve, reject) => {
-            fetch(self.getOption('write.url'), init).then(response => {
-                const acceptedStatus = self.getOption('write.acceptedStatus', [200, 201]);
+        return fetchData.call(this, init, 'write');
+    }
 
-                if (acceptedStatus.indexOf(response.status) > -1) {
-                    reject(response);
-                    return;
-                }
 
-                response.text().then((body) => {
+    /**
+     * @return {RestAPI}
+     */
+    getClone() {
+        const self = this;
+        return new RestAPI(self[internalSymbol].getRealSubject()['options'].read, self[internalSymbol].getRealSubject()['options'].write);
+    }
 
-                    let obj = {}, validation = {};
-                    try {
-                        obj = JSON.parse(body);
+}
 
-                        if (reportPath) {
-                            validation = (new Pathfinder(obj)).getVia(reportPath);
-                        }
 
+function fetchData(init, key, callback) {
 
-                    } catch (e) {
+    const self = this;
+    let response;
 
-                        if (body.length > 100) {
-                            body = body.substring(0, 97) + '...';
-                        }
 
-                        reject(new Error('the response does not contain a valid json (actual: ' + body + ').'));
-                        return;
-                    }
+    return fetch(self.getOption(key + '.url'), init).then(resp => {
+        response = resp;
 
-                    reject(new WriteError('the data cannot be written (response ' + response.status + ')', response, validation))
-                    return;
+        const acceptedStatus = self.getOption(key + '.acceptedStatus', [200]);
 
-                }).catch(reject);
+        if (acceptedStatus.indexOf(resp.status) === -1) {
+            throw Error('the data cannot be ' + key + ' (response ' + resp.status + ')')
+        }
 
+        return resp.text()
+    }).then(body => {
 
-            }).catch(reject);
+        let obj;
 
-        })
+        try {
+            obj = JSON.parse(body);
 
-    }
+        } catch (e) {
 
+            if (body.length > 100) {
+                body = body.substring(0, 97) + '...';
+            }
+
+            throw new Error('the response does not contain a valid json (actual: ' + body + ').');
+        }
+
+        if (callback && isFunction(callback)) {
+            callback(obj);
+        }
+        return response;
+
+    });
 
-    /**
-     * @return {RestAPI}
-     */
-    getClone() {
-        const self = this;
-        return new RestAPI(self[internalSymbol].getRealSubject()['options'].read, self[internalSymbol].getRealSubject()['options'].write);
-    }
 
 }
 
diff --git a/development/test/cases/data/datasource/server/restapi.mjs b/development/test/cases/data/datasource/server/restapi.mjs
index fac52b2b7..4a3c9eff6 100644
--- a/development/test/cases/data/datasource/server/restapi.mjs
+++ b/development/test/cases/data/datasource/server/restapi.mjs
@@ -7,7 +7,7 @@ import {validateObject} from "../../../../../../application/source/types/validat
 
 describe('RestAPI', function () {
 
-    let fetchReference; 
+    let fetchReference;
     let returnStatus;
 
     afterEach(() => {
@@ -28,9 +28,6 @@ describe('RestAPI', function () {
                                 a: "test"
                             }));
                         });
-                        
-                        
-                        
                     },
                     status: returnStatus
                 });
@@ -55,19 +52,23 @@ describe('RestAPI', function () {
         });
 
         it('write should ', function (done) {
-            const ds = new RestAPI({url: 'https://monsterjs.org/assets/world.json'}, 
-                {
-                    url: 'https://monsterjs.org/assets/world.json',
-                    acceptedStatus: [99]
-                })
+            const ds = new RestAPI({
+                    read: {
+                        url: 'https://monsterjs.org/assets/world.json'
+                    },
+                    write: {
+                        url: 'https://monsterjs.org/assets/world.json',
+                        acceptedStatus: [99]
+                    }
+                }
+            )
             ds.write().then(data => {
                 done("should not be here");
             }).catch(e => done());
         });
+    });
 
 
-    })
-
     describe('rw with errors', function () {
 
         it('read should throw exception', function (done) {
-- 
GitLab