@andersonalmeidax0/webcomponents 0.1.2 → 0.1.4

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.
@@ -1,6 +1,18 @@
1
1
  "use strict";
2
2
  /* ************************************************** */
3
3
  /* ************************************************** */
4
+ const ErrorConstants = {
5
+ PlatAPIError: "PlatAPIError",
6
+ PlatAPIReturnCodeError: "PlatAPIReturnCodeError",
7
+
8
+ PlatAPIAuthError: "PlatAPIAuthError",
9
+ PlatAPIForbidden: "PlatAPIForbidden",
10
+
11
+ PlatAPIDBNotFound: "PlatAPIDBNotFound",
12
+ PlatAPIDBIntegrityConstraint: "PlatAPIDBIntegrityConstraint",
13
+ };
14
+ /* ************************************************** */
15
+ /* ************************************************** */
4
16
  class PlatAPIError extends Error {
5
17
  constructor(message, type) {
6
18
  super(message);
@@ -38,4 +50,4 @@ class PlatAPIForbidden extends Error {
38
50
 
39
51
  //exports.PlatAPIDBNotFound = PlatAPIDBNotFound;
40
52
 
41
- export {PlatAPIError,PlatAPIReturnCodeError,PlatAPIAuthError,PlatAPIDBNotFound,PlatAPIDBIntegrityConstraint,PlatAPIForbidden};
53
+ export {ErrorConstants,PlatAPIError,PlatAPIReturnCodeError,PlatAPIAuthError,PlatAPIDBNotFound,PlatAPIDBIntegrityConstraint,PlatAPIForbidden};
@@ -0,0 +1,199 @@
1
+ /* eslint-disable no-unused-vars */
2
+ import {PlatAPIError,PlatAPIReturnCodeError,PlatAPIAuthError,PlatAPIDBNotFound,PlatAPIDBIntegrityConstraint,PlatAPIForbidden} from "./Errors";
3
+
4
+ //ERPNEXT API request: BODYTAG:data, RESPTAG:data,LISTTAG:null (só o array)
5
+ //https://frappeframework.com/docs/user/en/api/rest
6
+
7
+ //JSON API request: BODYTAG:data, RESPTAG:data,LISTTAG:null (só o array)
8
+ //https://jsonapi.org/format/#crud
9
+
10
+ //COIN GECKO: request: BODYTAG:null, RESPTAG:null,LISTTAG:null (só o array)
11
+ //https://api.coingecko.com/api/v3/coins/
12
+
13
+ //Oracle API request: BODYTAG:null, RESPTAG:null,LISTTAG:elements
14
+ //https://docs.oracle.com/en/cloud/saas/marketing/eloqua-rest-api/op-api-rest-1.0-data-account-post.html
15
+
16
+
17
+ var DEBUG_APIFETCH=true;
18
+
19
+ //TODO:
20
+ //1-tem que usar heranca para metodos new, validate, etc
21
+ //2-para seguir padrao JSON-API, os dados de entrada (POST/PUT) ficam em objeto "data" (ou NÃO... para simplificar o JSDOC...) ==> mas é padrao ERPNExt!!!
22
+ //3-Os dados de saida em "data" => qdo é um só é object, qdo sao vários é array
23
+ //4-Error: se tem erro, tem object "error" ou "errors"
24
+ //5-InsertedId ==> colocar junto no payload.data
25
+ //6-Auth: colocar no header como header "Authorization" e colocar o sid (que está em storage). O server irá validar.
26
+ //7-implementacao
27
+ /*
28
+ a.get sid from storage
29
+ b.chamada fetch3 (com POST,GET,ETC) e a URL `/{$typeName}/$vo.id`, PASSANDO (e FORMATANDO) BODY
30
+ c.verifica se deu erro (se 404 retorna not found)
31
+ d.pega wait r.data
32
+ e.set tem insertedID, seta no payload
33
+ f.se tem data, seta (se for collection.. verifica se campo "type", do primeiro item [0] é igual ao typeName)
34
+ g.senao erro
35
+ */
36
+ //8-gerar uma versao sem "data" para usar com Json-server
37
+ /*
38
+ ==> para tertar com ERPNext: tem que
39
+ 1-colocar no ar ERPNext (bench start assync ???)
40
+ 2-colocar no ar o ApiCRM (adapter)
41
+ 3-dar renew no crm.andermusic.com ==> certificado https
42
+ X-Colocar o MetalMarlek em outro server AWS ... com docker... com outra conta de mongodb "andermusicdevelopment" free.. com CI/CD
43
+ */
44
+
45
+ function getStorage(key) {
46
+ const itemStr = sessionStorage.getItem(key)
47
+ if (!itemStr) {
48
+ return null;
49
+ }
50
+ const item = JSON.parse(itemStr)
51
+ return item;
52
+ }
53
+
54
+ /* ************************************************** */
55
+ /* ************************************************** */
56
+ function getStorageWithExpiry(key) {
57
+ const itemStr = sessionStorage.getItem(key)
58
+ // if the item doesn't exist, return null
59
+ if (!itemStr) {
60
+ return null;
61
+ }
62
+ const item = JSON.parse(itemStr)
63
+ const now = new Date()
64
+ // compare the expiry time of the item with the current time
65
+ if (now.getTime() > item.expiry) {
66
+ // If the item is expired, delete the item from storage
67
+ // and return null
68
+ //alert('Session: expired'+key);
69
+ sessionStorage.removeItem(key)
70
+ return null
71
+ }
72
+ return item.value
73
+ }
74
+
75
+
76
+ /** **********************************************
77
+ *
78
+ ********************************************** */
79
+ class RestAPIAdapter {
80
+ tableName;
81
+ urlServer;
82
+ tagData;
83
+ /** ***********************
84
+ *
85
+ *********************** */
86
+ constructor(tableName,urlServer,tagData,token,pnewVO) {
87
+
88
+ this.tableName=tableName;
89
+ this.urlServer=urlServer;
90
+ this.tagData=tagData;
91
+ this.token=token;
92
+ if(pnewVO)this.newVO=pnewVO;
93
+ }
94
+ /** ***********************
95
+ *
96
+ *********************** */
97
+ newVO() { return {}; };
98
+ view2model(vo) { return vo;}
99
+ model2view(vo) { return vo; }
100
+ validate(vo) { return vo; }
101
+ /** ***********************
102
+ *
103
+ *********************** */
104
+ getParams(q,vo,entity){
105
+ if(q==="create") return {method:'POST',url:`/${entity}/`,body:vo}
106
+ if(q==="findByPK") return {method:'GET',url:`/${entity}/${vo._id}`,body:null};
107
+ if(q==="findByFK") return {method:'GET',url:`/${entity}`,body:null};
108
+ if(q==="findAll") return {method:'GET',url:`/${entity}`,body:null};
109
+ if(q==="update") return {method:'PUT',url:`/${entity}/${vo._id}`,body:vo}
110
+ if(q==="removeByPK") return {method:'DELETE',url:`/${entity}/${vo._id}`,body:null};
111
+
112
+ return {method:'INVALID',url:`/INVALID`,body:null};
113
+
114
+ }
115
+ /** ***********************
116
+ *
117
+ *********************** */
118
+ async getJSONResponse(response) {
119
+ var r=null;
120
+ r=await response.json();
121
+ if(DEBUG_APIFETCH)alert(JSON.stringify(r,null,2));
122
+ if(r.error)
123
+ throw new PlatAPIReturnCodeError(r.error.message);
124
+ return r;
125
+ }
126
+ /** ***********************
127
+ *
128
+ *********************** */
129
+ async callAPI(q,vo,context,filter) {
130
+ var r = null;
131
+ var ptoken=this.token?this.token:(getStorageWithExpiry('sid'));
132
+ //if(ptoken==null)
133
+ // throw new PlatAPIAuthError( `An error has occured: ${response.status}`);
134
+
135
+ var {method,url,body}=this.getParams(q,vo,this.urlServer+"/"+this.tableName,filter);
136
+
137
+ const response = await this.myFetch3(ptoken,url,method,body);
138
+ if (!response.ok) {
139
+ if(response.status===404)
140
+ throw new PlatAPIDBNotFound( `An error has occured: ${response.status}`);
141
+ if(response.status===403)
142
+ throw new PlatAPIForbidden( `An error has occured: ${response.status}`);
143
+ if(response.status===401)
144
+ throw new PlatAPIAuthError( `An error has occured: ${response.status}`);
145
+ throw new PlatAPIReturnCodeError();
146
+ }
147
+ r=await this.getJSONResponse(response);
148
+
149
+ //tag de dados pode ser nada,result, data
150
+ if(this.tagData==null) return r;
151
+
152
+ var respBlock=this.tagData;
153
+ if(r[respBlock])
154
+ r[respBlock].insertedId=r.insertedId;
155
+ if(r[respBlock]) return r[respBlock];
156
+ throw new PlatAPIError('Invalid payload response');
157
+ };
158
+ /** ***********************
159
+ *
160
+ *********************** */
161
+ async create(vo,context) {
162
+ return await this.callAPI('create',vo,context)
163
+ };
164
+ async findByPK(id,context) {
165
+ //alert(JSON.stringify(vo));
166
+ return await this.callAPI('findByPK',{_id:id},context)
167
+ };
168
+ async findByFK(fkArr,context) {
169
+ return await this.callAPI('findByFK',fkArr,context)
170
+ };
171
+ async update(vo,context) {
172
+ alert(JSON.stringify(vo));
173
+ return await this.callAPI('update',vo,context)
174
+ };
175
+ async removeByPK(vo,context) {
176
+ return await this.callAPI('removeByPK',vo,context)
177
+ };
178
+ async findAll(context,filter) {
179
+ return await this.callAPI('findAll',null,context,filter)
180
+ };
181
+ /** ***********************
182
+ *
183
+ *********************** */
184
+ async myFetch3 (token,url,method,body) {
185
+ if(DEBUG_APIFETCH)alert("url:"+url);
186
+ if(DEBUG_APIFETCH)alert("m:"+method);
187
+ if(DEBUG_APIFETCH)alert("body:"+body);
188
+ if(DEBUG_APIFETCH)alert("token:"+JSON.stringify(token));
189
+
190
+ var r = await fetch(url,
191
+ {
192
+ method: method,
193
+ headers: { "content-type": "application/json", "Authorization": token },
194
+ body: body?JSON.stringify(body):null
195
+ });
196
+ return r;
197
+ }
198
+ }
199
+ export {RestAPIAdapter};
@@ -1,20 +1,21 @@
1
1
  import React from "react";
2
2
  import {XButton} from "../XButton.jsx"
3
- import {XInputExternal} from "../XInput.jsx"
4
- import {XSelect3} from "../XSelect"
5
- import {XTextArea} from "../XTextArea"
6
- import {XCheckbox} from "../XCheckbox.jsx"
7
- import {XDateSelect} from "../XDateSelect.jsx"
3
+ //import {XInputExternal} from "../XInput.jsx"
4
+ //import {XSelect3} from "../XSelect"
5
+ //import {XTextArea} from "../XTextArea"
6
+ //import {XCheckbox} from "../XCheckbox.jsx"
7
+ //import {XDateSelect} from "../XDateSelect.jsx"
8
8
 
9
9
 
10
10
 
11
11
 
12
- import { XTableRead } from "./XTableRead.jsx";
12
+ //import { XTableRead } from "./XTableRead.jsx";
13
13
  import { XFormEdit } from "./XFormEdit.jsx";
14
- import { JZInPlaceListComponent } from "./JZInPlaceListComponent.jsx";
14
+ //import { JZInPlaceListComponent } from "./JZInPlaceListComponent.jsx";
15
15
 
16
16
 
17
- import {PlatAPIError,PlatAPIReturnCodeError,PlatAPIAuthError,PlatAPIDBNotFound,PlatAPIDBIntegrityConstraint,PlatAPIForbidden} from "./Errors.js";
17
+ import {PlatAPIError,PlatAPIReturnCodeError,PlatAPIAuthError,PlatAPIDBNotFound,PlatAPIDBIntegrityConstraint,PlatAPIForbidden} from "../Errors.js";
18
+ import {ErrorConstants} from "../Errors.js";
18
19
  import { ErrorCard } from "./ErrorCard";
19
20
  import { ErrorCardAuth } from "./ErrorCardAuth";
20
21
 
@@ -15,7 +15,7 @@ import { JZEditComponent } from "./JZEditComponent.jsx";
15
15
  import { JZInPlaceListComponent } from "./JZInPlaceListComponent.jsx";
16
16
 
17
17
 
18
- import {PlatAPIError,PlatAPIReturnCodeError,PlatAPIAuthError,PlatAPIDBNotFound,PlatAPIDBIntegrityConstraint,PlatAPIForbidden} from "./Errors.js";
18
+ import {PlatAPIError,PlatAPIReturnCodeError,PlatAPIAuthError,PlatAPIDBNotFound,PlatAPIDBIntegrityConstraint,PlatAPIForbidden} from "../Errors.js";
19
19
  import { ErrorCard } from "./ErrorCard";
20
20
  import { ErrorCardAuth } from "./ErrorCardAuth";
21
21
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andersonalmeidax0/webcomponents",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "webcomponents",
5
5
  "main": "webcomponents",
6
6
  "scripts": {
package/releasenotes.txt CHANGED
@@ -1,12 +1,15 @@
1
1
  0.1.0: beta
2
2
  0.1.1: add all components
3
3
  0.1.2: with text labels for buttons
4
+ 0.1.3: RestAPIAdapter init
5
+ 0.1.4: Error move to root
6
+
4
7
 
5
8
  TODO
6
9
  -change "Errors" => string contants
7
10
  -add "textIcon=true" option para JZEditTable ==> OK
8
- -create NPM
9
- -test
11
+ -create NPM OK
12
+ -test OK
10
13
 
11
14
  -readme: document capacities
12
15
  JZ read and form: format specs, types
@@ -17,8 +20,11 @@ TODO
17
20
  TODO:
18
21
  Exepctions de erros, criador para a)evitar tratar StatusCodesHttp e b)permitir "try catch" de erros "subindo" no stack
19
22
  Expection "genericas" assim é só import de constantes, e tratar em qualquer camada com "Error.message==xxxx"
23
+
20
24
  Package separado, assim dá para usar na aplicação "Error.message==xxxx", em npms, e também no server, com imports redundantes
21
- 1-criar test cases para PlatAPIError
25
+ ==> ACHO QUE NAO PRECISA, POIS O CLIENT E INDEP DO SERVER (OS ERROS TRAFEGAM VIA STATUSCODES!!!
26
+
27
+ 1-criar test cases para PlatAPIError ==>
22
28
  2-criar uma classe com constantes string de error APIErrors
23
29
  3-Incluir APIAdapter no código de JZComponents
24
30
  4-Tratar erros vendo se e.message==APIErrors.API<messageCode>