@wishknish/knishio-client-js 0.5.2 → 0.6.1

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.
Files changed (133) hide show
  1. package/README.md +207 -274
  2. package/dist/client.iife.js +533 -0
  3. package/package.json +37 -79
  4. package/src/.babelrc +0 -22
  5. package/src/Atom.js +171 -132
  6. package/src/AtomMeta.js +76 -50
  7. package/src/AuthToken.js +38 -47
  8. package/src/KnishIOClient.js +934 -987
  9. package/src/Meta.js +15 -17
  10. package/src/Molecule.js +423 -494
  11. package/src/PolicyMeta.js +32 -41
  12. package/src/TokenUnit.js +30 -32
  13. package/src/Wallet.js +275 -265
  14. package/src/exception/AtomIndexException.js +4 -8
  15. package/src/exception/AtomsMissingException.js +4 -6
  16. package/src/exception/AuthorizationRejectedException.js +4 -5
  17. package/src/exception/BalanceInsufficientException.js +4 -8
  18. package/src/exception/BaseException.js +6 -8
  19. package/src/exception/BatchIdException.js +5 -7
  20. package/src/exception/CodeException.js +4 -8
  21. package/src/{libraries/ApolloLink/HttpLink.js → exception/DecryptionKeyException.js} +12 -15
  22. package/src/exception/InvalidResponseException.js +4 -5
  23. package/src/exception/MetaMissingException.js +4 -6
  24. package/src/exception/MolecularHashMismatchException.js +4 -6
  25. package/src/exception/MolecularHashMissingException.js +4 -5
  26. package/src/exception/NegativeAmountException.js +4 -5
  27. package/src/exception/PolicyInvalidException.js +4 -4
  28. package/src/exception/SignatureMalformedException.js +4 -5
  29. package/src/exception/SignatureMismatchException.js +4 -5
  30. package/src/exception/StackableUnitAmountException.js +4 -5
  31. package/src/exception/StackableUnitDecimalsException.js +4 -5
  32. package/src/exception/TransferBalanceException.js +4 -5
  33. package/src/exception/TransferMalformedException.js +4 -5
  34. package/src/exception/TransferMismatchedException.js +4 -5
  35. package/src/exception/TransferRemainderException.js +4 -5
  36. package/src/exception/TransferToSelfException.js +4 -5
  37. package/src/exception/TransferUnbalancedException.js +4 -5
  38. package/src/exception/UnauthenticatedException.js +4 -5
  39. package/src/{libraries/ApolloLink/AuthLink.js → exception/WalletCredentialException.js} +12 -40
  40. package/src/exception/WalletShadowException.js +4 -5
  41. package/src/exception/WrongTokenTypeException.js +4 -5
  42. package/src/exception/index.js +26 -26
  43. package/src/index.js +8 -10
  44. package/src/instance/Rules/Callback.js +91 -93
  45. package/src/instance/Rules/Condition.js +21 -23
  46. package/src/instance/Rules/Meta.js +13 -14
  47. package/src/instance/Rules/Rule.js +39 -43
  48. package/src/instance/Rules/exception/RuleArgumentException.js +4 -4
  49. package/src/libraries/CheckMolecule.js +253 -232
  50. package/src/libraries/Decimal.js +13 -17
  51. package/src/libraries/Dot.js +74 -48
  52. package/src/libraries/Hex.js +49 -54
  53. package/src/libraries/array.js +50 -41
  54. package/src/libraries/crypto.js +20 -27
  55. package/src/libraries/strings.js +58 -91
  56. package/src/libraries/urql/UrqlClientWrapper.js +166 -0
  57. package/src/mutation/Mutation.js +44 -25
  58. package/src/mutation/MutationActiveSession.js +12 -12
  59. package/src/mutation/MutationClaimShadowWallet.js +15 -17
  60. package/src/mutation/MutationCreateIdentifier.js +11 -12
  61. package/src/mutation/MutationCreateMeta.js +11 -12
  62. package/src/mutation/MutationCreateRule.js +11 -12
  63. package/src/mutation/MutationCreateToken.js +18 -13
  64. package/src/mutation/MutationCreateWallet.js +9 -11
  65. package/src/mutation/MutationDepositBufferToken.js +7 -9
  66. package/src/mutation/MutationLinkIdentifier.js +12 -14
  67. package/src/mutation/MutationProposeMolecule.js +24 -25
  68. package/src/mutation/MutationRequestAuthorization.js +9 -10
  69. package/src/mutation/MutationRequestAuthorizationGuest.js +12 -15
  70. package/src/mutation/MutationRequestTokens.js +11 -14
  71. package/src/mutation/MutationTransferTokens.js +11 -14
  72. package/src/mutation/MutationWithdrawBufferToken.js +7 -10
  73. package/src/query/Query.js +62 -36
  74. package/src/query/QueryActiveSession.js +11 -13
  75. package/src/query/QueryAtom.js +75 -76
  76. package/src/query/QueryBalance.js +11 -12
  77. package/src/query/QueryBatch.js +17 -14
  78. package/src/query/QueryBatchHistory.js +16 -13
  79. package/src/query/QueryContinuId.js +13 -10
  80. package/src/query/QueryMetaType.js +45 -57
  81. package/src/query/QueryMetaTypeViaAtom.js +49 -57
  82. package/src/query/QueryPolicy.js +11 -12
  83. package/src/query/QueryToken.js +11 -13
  84. package/src/query/QueryUserActivity.js +11 -13
  85. package/src/query/QueryWalletBundle.js +15 -47
  86. package/src/query/QueryWalletList.js +15 -16
  87. package/src/response/Response.js +29 -34
  88. package/src/response/ResponseActiveSession.js +6 -6
  89. package/src/response/ResponseAtom.js +29 -30
  90. package/src/response/ResponseAuthorizationGuest.js +17 -18
  91. package/src/response/ResponseBalance.js +12 -13
  92. package/src/response/ResponseClaimShadowWallet.js +1 -1
  93. package/src/response/ResponseContinuId.js +21 -22
  94. package/src/response/ResponseCreateIdentifier.js +1 -1
  95. package/src/response/ResponseCreateMeta.js +1 -1
  96. package/src/response/ResponseCreateRule.js +1 -1
  97. package/src/response/ResponseCreateToken.js +1 -1
  98. package/src/response/ResponseCreateWallet.js +1 -1
  99. package/src/response/ResponseLinkIdentifier.js +9 -10
  100. package/src/response/ResponseMetaBatch.js +6 -8
  101. package/src/response/ResponseMetaType.js +19 -20
  102. package/src/response/ResponseMetaTypeViaAtom.js +19 -19
  103. package/src/response/ResponsePolicy.js +14 -15
  104. package/src/response/ResponseProposeMolecule.js +27 -30
  105. package/src/response/ResponseQueryActiveSession.js +20 -23
  106. package/src/response/ResponseQueryUserActivity.js +11 -12
  107. package/src/response/ResponseRequestAuthorization.js +11 -16
  108. package/src/response/ResponseRequestAuthorizationGuest.js +18 -21
  109. package/src/response/ResponseRequestTokens.js +1 -1
  110. package/src/response/ResponseTransferTokens.js +8 -9
  111. package/src/response/ResponseWalletBundle.js +16 -17
  112. package/src/response/ResponseWalletList.js +44 -47
  113. package/src/subscribe/ActiveSessionSubscribe.js +5 -6
  114. package/src/subscribe/ActiveWalletSubscribe.js +5 -6
  115. package/src/subscribe/CreateMoleculeSubscribe.js +5 -5
  116. package/src/subscribe/Subscribe.js +26 -26
  117. package/src/subscribe/WalletStatusSubscribe.js +5 -6
  118. package/src/versions/HashAtom.js +78 -0
  119. package/src/versions/Version4.js +34 -0
  120. package/src/versions/index.js +5 -0
  121. package/dist/client.umd.js +0 -453
  122. package/src/httpClient/ApolloClient.js +0 -245
  123. package/src/libraries/ApolloLink/CipherLink.js +0 -117
  124. package/src/libraries/ApolloLink/Client.js +0 -231
  125. package/src/libraries/ApolloLink/PusherLink.js +0 -234
  126. package/src/libraries/ApolloLink/handler.js +0 -106
  127. package/src/libraries/Base58.js +0 -71
  128. package/src/libraries/Base64.js +0 -40
  129. package/src/libraries/BaseX.js +0 -91
  130. package/src/libraries/Soda.js +0 -93
  131. package/src/query/QueryMetaInstance.js +0 -99
  132. package/src/test/Test.js +0 -670
  133. package/src/test/TestTokenUnit.js +0 -340
@@ -1,27 +1,21 @@
1
- import bigInt from 'big-integer';
2
- import Hex from './Hex';
3
- import {
4
- decode as decodeBase64,
5
- encode as encodeBase64
6
- } from '@stablelib/base64';
7
- import getRandomValues from 'get-random-values';
8
-
9
- if ( !String.prototype.trim ) {
1
+ import Hex from './Hex'
2
+
3
+ if (!String.prototype.trim) {
10
4
  String.prototype.trim = function () {
11
- return this.replace( /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '' );
12
- };
5
+ return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '')
6
+ }
13
7
  }
14
8
 
15
- if ( !String.prototype.toCamelCase ) {
9
+ if (!String.prototype.toCamelCase) {
16
10
  String.prototype.toCamelCase = function () {
17
- return this.toLowerCase().replace( /[^a-zA-Z0-9]+(.)/g, ( m, chr ) => chr.toUpperCase() );
18
- };
11
+ return this.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase())
12
+ }
19
13
  }
20
14
 
21
- if ( !String.prototype.toSnakeCase ) {
15
+ if (!String.prototype.toSnakeCase) {
22
16
  String.prototype.toSnakeCase = function () {
23
- return this.replace( /[A-Z]/g, letter => `_${ letter.toLowerCase() }` );
24
- };
17
+ return this.replace(/[A-Z]/g, letter => `_${ letter.toLowerCase() }`)
18
+ }
25
19
  }
26
20
 
27
21
  /**
@@ -31,16 +25,15 @@ if ( !String.prototype.toSnakeCase ) {
31
25
  * @param size
32
26
  * @return {any[]}
33
27
  */
34
- export function chunkSubstr ( str, size ) {
35
-
36
- const numChunks = Math.ceil( str.length / size ),
37
- chunks = [];
28
+ export function chunkSubstr (str, size) {
29
+ const numChunks = Math.ceil(str.length / size)
30
+ const chunks = []
38
31
 
39
- for ( let chunkIndex = 0, o = 0; chunkIndex < numChunks; ++chunkIndex, o += size ) {
40
- chunks[ chunkIndex ] = str.substr( o, size );
32
+ for (let chunkIndex = 0, o = 0; chunkIndex < numChunks; ++chunkIndex, o += size) {
33
+ chunks[chunkIndex] = str.substr(o, size)
41
34
  }
42
35
 
43
- return chunks;
36
+ return chunks
44
37
  }
45
38
 
46
39
  /**
@@ -50,78 +43,52 @@ export function chunkSubstr ( str, size ) {
50
43
  * @param alphabet
51
44
  * @return {string}
52
45
  */
53
- export function randomString ( length = 256, alphabet = 'abcdef0123456789' ) {
54
-
55
- let array = new Uint8Array( length );
46
+ export function randomString (length = 256, alphabet = 'abcdef0123456789') {
47
+ let array = new Uint8Array(length)
56
48
 
57
- array = getRandomValues( array );
49
+ array = crypto.getRandomValues(array)
58
50
 
59
- array = array.map( x => alphabet.charCodeAt( x % alphabet.length ) );
51
+ array = array.map(x => alphabet.charCodeAt(x % alphabet.length))
60
52
 
61
- return String.fromCharCode.apply( null, array );
53
+ return String.fromCharCode.apply(null, array)
62
54
  }
63
55
 
64
56
  /**
65
57
  * Convert charset between bases and alphabets
66
58
  *
67
59
  * @param src
68
- * @param fromBase
69
- * @param toBase
70
- * @param srcSymbolTable
71
- * @param destSymbolTable
60
+ * @param {int} fromBase
61
+ * @param {int} toBase
62
+ * @param { string} srcSymbolTable
63
+ * @param {string} destSymbolTable
72
64
  * @return {boolean|string|number}
73
65
  */
74
- export function charsetBaseConvert ( src, fromBase, toBase, srcSymbolTable, destSymbolTable ) {
75
-
76
- // From: convert.js: http://rot47.net/_js/convert.js
77
- // http://rot47.net
78
- // http://helloacm.com
79
- // http://codingforspeed.com
80
- // Dr Zhihua Lai
81
- //
82
- // Modified by MLM to work with BigInteger: https://github.com/peterolson/BigInteger.js
83
- // This is able to convert extremely large numbers; At any base equal to or less than the symbol table length
84
-
85
- // The reasoning behind capital first is because it comes first in an ASCII/Unicode character map
86
- // 96 symbols support up to base 96
87
- const baseSymbols = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:\'",<.>/?¿¡';
88
-
89
- // Default the symbol table to a nice default table that supports up to base 96
90
- srcSymbolTable = srcSymbolTable ? srcSymbolTable : baseSymbols;
91
- // Default the desttable equal to the srctable if it isn't defined
92
- destSymbolTable = destSymbolTable ? destSymbolTable : srcSymbolTable;
93
-
94
- // Make sure we are not trying to convert out of the symbol table range
95
- if ( fromBase > srcSymbolTable.length || toBase > destSymbolTable.length ) {
96
-
97
- console.warn( 'Strings::charsetBaseConvert() - Can\'t convert', src, 'to base', toBase, 'greater than symbol table length. src-table:', srcSymbolTable.length, 'dest-table:', destSymbolTable.length );
98
- return false;
66
+ export function charsetBaseConvert (src, fromBase, toBase, srcSymbolTable, destSymbolTable) {
67
+ const baseSymbols = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:\'",<.>/?¿¡'
68
+ srcSymbolTable = srcSymbolTable || baseSymbols
69
+ destSymbolTable = destSymbolTable || srcSymbolTable
70
+
71
+ if (fromBase > srcSymbolTable.length || toBase > destSymbolTable.length) {
72
+ console.warn('Strings::charsetBaseConvert() - Can\'t convert', src, 'to base', toBase, 'greater than symbol table length. src-table:', srcSymbolTable.length, 'dest-table:', destSymbolTable.length)
73
+ return false
99
74
  }
100
75
 
101
- // First convert to base 10
102
- let val = bigInt( 0 );
103
-
104
- for ( let charIndex = 0; charIndex < src.length; charIndex++ ) {
105
- val = val.multiply( fromBase ).add( srcSymbolTable.indexOf( src.charAt( charIndex ) ) );
106
- }
107
-
108
- if ( val.lesser( 0 ) ) {
109
- return 0;
76
+ // Convert from source base to BigInt in base 10
77
+ let val = BigInt(0)
78
+ for (let charIndex = 0; charIndex < src.length; charIndex++) {
79
+ val = val * BigInt(fromBase) + BigInt(srcSymbolTable.indexOf(src.charAt(charIndex)))
110
80
  }
111
81
 
112
- // Then covert to any base
113
- let r = val.mod( toBase ),
114
- res = destSymbolTable.charAt( r ),
115
- q = val.divide( toBase );
116
-
117
- while ( !q.equals( 0 ) ) {
118
-
119
- r = q.mod( toBase );
120
- q = q.divide( toBase );
121
- res = destSymbolTable.charAt( r ) + res;
82
+ // Convert from BigInt in base 10 to destination base
83
+ let res = ''
84
+ while (val > 0) {
85
+ const r = val % BigInt(toBase)
86
+ res = destSymbolTable.charAt(Number(r)) + res
87
+ val /= BigInt(toBase)
122
88
  }
123
89
 
124
- return res;
90
+ // If the result is empty, it means the source was 0
91
+ return res || '0'
125
92
  }
126
93
 
127
94
  /**
@@ -130,8 +97,8 @@ export function charsetBaseConvert ( src, fromBase, toBase, srcSymbolTable, dest
130
97
  * @param byteArray
131
98
  * @return {string}
132
99
  */
133
- export function bufferToHexString ( byteArray ) {
134
- return Hex.toHex( byteArray, {} );
100
+ export function bufferToHexString (byteArray) {
101
+ return Hex.toHex(byteArray, {})
135
102
  }
136
103
 
137
104
  /**
@@ -140,8 +107,8 @@ export function bufferToHexString ( byteArray ) {
140
107
  * @param hexString
141
108
  * @return {Uint8Array}
142
109
  */
143
- export function hexStringToBuffer ( hexString ) {
144
- return Hex.toUint8Array( hexString );
110
+ export function hexStringToBuffer (hexString) {
111
+ return Hex.toUint8Array(hexString)
145
112
  }
146
113
 
147
114
  /**
@@ -150,8 +117,8 @@ export function hexStringToBuffer ( hexString ) {
150
117
  * @param string
151
118
  * @return {string}
152
119
  */
153
- export function hexToBase64 ( string ) {
154
- return encodeBase64( Hex.toUint8Array( string ) );
120
+ export function hexToBase64 (string) {
121
+ return Buffer.from(string, 'hex').toString('base64')
155
122
  }
156
123
 
157
124
  /**
@@ -160,22 +127,22 @@ export function hexToBase64 ( string ) {
160
127
  * @param {string} string
161
128
  * @return {string}
162
129
  */
163
- export function base64ToHex ( string ) {
164
- return Hex.toHex( decodeBase64( string ), {} );
130
+ export function base64ToHex (string) {
131
+ return Buffer.from(string, 'base64').toString('hex')
165
132
  }
166
133
 
167
134
  /**
168
135
  * @param {string} str
169
136
  * @return {boolean}
170
137
  */
171
- export function isHex ( str ) {
172
- return /^[A-F0-9]+$/i.test( str );
138
+ export function isHex (str) {
139
+ return /^[A-F0-9]+$/i.test(str)
173
140
  }
174
141
 
175
142
  /**
176
143
  * @param {string} str
177
144
  * @return {boolean}
178
145
  */
179
- export function isNumeric( str ) {
180
- return (typeof(str) === 'number' || typeof(str) === 'string' && str.trim() !== '') && !isNaN(str);
146
+ export function isNumeric (str) {
147
+ return (typeof (str) === 'number' || (typeof (str) === 'string' && str.trim() !== '')) && !isNaN(str)
181
148
  }
@@ -0,0 +1,166 @@
1
+ import {
2
+ createClient,
3
+ subscriptionExchange,
4
+ cacheExchange,
5
+ fetchExchange
6
+ } from '@urql/core'
7
+ import { createClient as createWSClient } from 'graphql-ws'
8
+ import { pipe, map } from 'wonka'
9
+
10
+ class UrqlClientWrapper {
11
+ constructor ({ serverUri, socket = null, encrypt = false }) {
12
+ this.$__client = this.createUrqlClient({ serverUri, socket, encrypt })
13
+ this.$__authToken = ''
14
+ this.$__pubkey = null
15
+ this.$__wallet = null
16
+ this.serverUri = serverUri
17
+ this.soketi = socket
18
+ this.cipherLink = !!encrypt
19
+ this.$__subscriptionManager = new Map()
20
+ }
21
+
22
+ createUrqlClient ({ serverUri, socket, encrypt }) {
23
+ const exchanges = [cacheExchange, fetchExchange]
24
+
25
+ // Add subscription support if socket is configured
26
+ if (socket && socket.socketUri) {
27
+ const wsClient = createWSClient({
28
+ url: socket.socketUri,
29
+ connectionParams: () => ({
30
+ authToken: this.$__authToken
31
+ })
32
+ })
33
+
34
+ exchanges.push(subscriptionExchange({
35
+ forwardSubscription: operation => ({
36
+ subscribe: sink => {
37
+ const disposable = wsClient.subscribe(operation, sink)
38
+ return { unsubscribe: disposable }
39
+ }
40
+ })
41
+ }))
42
+ }
43
+
44
+ return createClient({
45
+ url: serverUri,
46
+ exchanges,
47
+ fetchOptions: () => ({
48
+ headers: {
49
+ 'X-Auth-Token': this.$__authToken
50
+ }
51
+ })
52
+ })
53
+ }
54
+
55
+ setAuthData ({ token, pubkey, wallet }) {
56
+ this.$__authToken = token
57
+ this.$__pubkey = pubkey
58
+ this.$__wallet = wallet
59
+
60
+ // Recreate client with new auth data
61
+ this.$__client = this.createUrqlClient({
62
+ serverUri: this.serverUri,
63
+ socket: this.soketi,
64
+ encrypt: !!this.cipherLink
65
+ })
66
+ }
67
+
68
+ async query (request) {
69
+ const { query, variables } = request
70
+ const result = await this.$__client.query(query, variables).toPromise()
71
+ return this.formatResponse(result)
72
+ }
73
+
74
+ async mutate (request) {
75
+ const { mutation, variables } = request
76
+ const result = await this.$__client.mutation(mutation, variables).toPromise()
77
+ return this.formatResponse(result)
78
+ }
79
+
80
+ subscribe (request, closure) {
81
+ const { query, variables, operationName } = request
82
+
83
+ const { unsubscribe } = pipe(
84
+ this.$__client.subscription(query, variables),
85
+ map(result => {
86
+ closure(this.formatResponse(result))
87
+ })
88
+ ).subscribe(() => {})
89
+
90
+ // Store subscription for later cleanup
91
+ this.$__subscriptionManager.set(operationName, { unsubscribe })
92
+
93
+ return {
94
+ unsubscribe: () => this.unsubscribe(operationName)
95
+ }
96
+ }
97
+
98
+ formatResponse (result) {
99
+ // Match old Apollo response format
100
+ return {
101
+ data: result.data,
102
+ errors: result.error ? [result.error] : undefined
103
+ }
104
+ }
105
+
106
+ socketDisconnect () {
107
+ if (this.soketi) {
108
+ // Unsubscribe from all active subscriptions
109
+ this.unsubscribeAll()
110
+ }
111
+ }
112
+
113
+ unsubscribe (operationName) {
114
+ const subscription = this.$__subscriptionManager.get(operationName)
115
+ if (subscription) {
116
+ subscription.unsubscribe()
117
+ this.$__subscriptionManager.delete(operationName)
118
+ }
119
+ }
120
+
121
+ unsubscribeAll () {
122
+ this.$__subscriptionManager.forEach((subscription, operationName) => {
123
+ this.unsubscribe(operationName)
124
+ })
125
+ }
126
+
127
+ unsubscribeFromChannel (operationName) {
128
+ this.unsubscribe(operationName)
129
+ }
130
+
131
+ setEncryption (encrypt = false) {
132
+ this.cipherLink = encrypt
133
+ this.$__client = this.createUrqlClient({
134
+ serverUri: this.serverUri,
135
+ socket: this.soketi,
136
+ encrypt
137
+ })
138
+ }
139
+
140
+ getAuthToken () { return this.$__authToken }
141
+ getPubKey () { return this.$__pubkey }
142
+ getWallet () { return this.$__wallet }
143
+ getServerUri () { return this.serverUri }
144
+ getSocketUri () { return this.soketi ? this.soketi.socketUri : null }
145
+ getUri () { return this.serverUri }
146
+
147
+ setUri (uri) {
148
+ this.serverUri = uri
149
+ this.$__client = this.createUrqlClient({
150
+ serverUri: uri,
151
+ socket: this.soketi,
152
+ encrypt: !!this.cipherLink
153
+ })
154
+ }
155
+
156
+ setSocketUri ({ socketUri, appKey }) {
157
+ this.soketi = { socketUri, appKey }
158
+ this.$__client = this.createUrqlClient({
159
+ serverUri: this.serverUri,
160
+ socket: this.soketi,
161
+ encrypt: !!this.cipherLink
162
+ })
163
+ }
164
+ }
165
+
166
+ export default UrqlClientWrapper
@@ -45,49 +45,68 @@ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
45
45
 
46
46
  License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
- import Query from '../query/Query';
48
+ import Query from '../query/Query'
49
+ import Response from '../response/Response'
49
50
 
50
51
  /**
51
52
  * Base class used to construct various GraphQL mutations
52
53
  */
53
54
  export default class Mutation extends Query {
54
- /**
55
- *
56
- * @param {ApolloClient} apolloClient
57
- */
58
- constructor ( apolloClient ) {
59
- super( apolloClient );
60
- }
61
-
62
55
  /**
63
56
  * Creates a new Request for the given parameters
64
57
  *
65
58
  * @param {{}} variables
66
59
  * @returns {{variables: (Object|null), query: null}}
67
60
  */
68
- createQuery ( { variables = null } ) {
69
- const request = super.createQuery( { variables } );
70
- request.mutation = request.query;
71
- delete request.query;
72
- return request;
61
+ createQuery ({ variables = null }) {
62
+ const request = super.createQuery({ variables })
63
+ request.mutation = request.query
64
+ delete request.query
65
+ return request
73
66
  }
74
67
 
75
68
  /**
76
- * Sends the Query to a Knish.IO node and returns the Response
77
- *
78
- * @param variables
79
- * @returns {Promise<Response>}
69
+ * Sends the Mutation to a Knish.IO node and returns the Response
70
+ * @param {Object||null} variables
71
+ * @param {Object||null} context
72
+ * @returns {Promise<Response|null>}
80
73
  */
81
- async execute ( { variables = null } ) {
82
-
83
- this.$__request = this.createQuery( {
74
+ async execute ({ variables = {}, context = {} }) {
75
+ this.$__request = this.createQuery({
84
76
  variables
85
- } );
77
+ })
78
+
79
+ const mergedContext = {
80
+ ...context,
81
+ ...this.createQueryContext()
82
+ }
86
83
 
87
- let response = await this.client.mutate( this.$__request );
84
+ try {
85
+ const mutationParams = {
86
+ ...this.$__request,
87
+ context: mergedContext
88
+ }
89
+ const response = await this.client.mutate(mutationParams)
88
90
 
89
- this.$__response = await this.createResponseRaw( response );
91
+ this.$__response = await this.createResponseRaw(response)
92
+
93
+ return this.$__response
94
+ } catch (error) {
95
+ if (error.name === 'AbortError') {
96
+ this.knishIOClient.log('warn', 'Mutation was cancelled')
97
+ // You might want to create a custom response for cancelled mutations
98
+ return new Response({
99
+ query: this,
100
+ json: { data: null, errors: [{ message: 'Mutation was cancelled' }] }
101
+ })
102
+ } else {
103
+ throw error
104
+ }
105
+ }
106
+ }
90
107
 
91
- return this.$__response;
108
+ createQueryContext () {
109
+ // Override this method in subclasses if needed
110
+ return {}
92
111
  }
93
112
  }
@@ -45,21 +45,21 @@ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
45
45
 
46
46
  License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
- import Mutation from '../mutation/Mutation';
49
- import ResponseActiveSession from '../response/ResponseActiveSession';
50
- import { gql } from '@apollo/client/core';
48
+ import Mutation from '../mutation/Mutation'
49
+ import ResponseActiveSession from '../response/ResponseActiveSession'
50
+ import { gql } from '@urql/core'
51
51
 
52
52
  /**
53
53
  * Mutation for declaring an active User Session with a given MetaAsset
54
54
  */
55
55
  export default class MutationActiveSession extends Mutation {
56
56
  /**
57
- * Class constructor
58
- *
59
- * @param apolloClient
57
+ * @param {UrqlClientWrapper} graphQLClient
58
+ * @param {KnishIOClient} knishIOClient
60
59
  */
61
- constructor ( apolloClient ) {
62
- super( apolloClient );
60
+ constructor (graphQLClient, knishIOClient) {
61
+ super(graphQLClient, knishIOClient)
62
+
63
63
  this.$__query = gql`mutation(
64
64
  $bundleHash: String!,
65
65
  $metaType: String!,
@@ -88,7 +88,7 @@ export default class MutationActiveSession extends Mutation {
88
88
  createdAt,
89
89
  updatedAt
90
90
  }
91
- }`;
91
+ }`
92
92
  }
93
93
 
94
94
  /**
@@ -97,10 +97,10 @@ export default class MutationActiveSession extends Mutation {
97
97
  * @param {object} json
98
98
  * @return {ResponseActiveSession}
99
99
  */
100
- createResponse ( json ) {
101
- return new ResponseActiveSession( {
100
+ createResponse (json) {
101
+ return new ResponseActiveSession({
102
102
  query: this,
103
103
  json
104
- } );
104
+ })
105
105
  }
106
106
  }
@@ -45,9 +45,9 @@ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
45
45
 
46
46
  License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
- import MutationProposeMolecule from './MutationProposeMolecule';
49
- import Wallet from '../Wallet';
50
- import ResponseClaimShadowWallet from '../response/ResponseClaimShadowWallet';
48
+ import MutationProposeMolecule from './MutationProposeMolecule'
49
+ import Wallet from '../Wallet'
50
+ import ResponseClaimShadowWallet from '../response/ResponseClaimShadowWallet'
51
51
 
52
52
  /**
53
53
  * Mutation for claiming a Shadow Wallet
@@ -59,22 +59,20 @@ export default class MutationClaimShadowWallet extends MutationProposeMolecule {
59
59
  * @param {string} token
60
60
  * @param {string|null} batchId
61
61
  */
62
- fillMolecule ( {
62
+ fillMolecule ({
63
63
  token,
64
64
  batchId = null
65
- } ) {
66
- let wallet = Wallet.create( {
67
- secretOrBundle: this.$__molecule.secret,
65
+ }) {
66
+ const wallet = Wallet.create({
67
+ secret: this.$__molecule.secret,
68
+ bundle: this.$__molecule.bundle,
68
69
  token,
69
70
  batchId
70
- } );
71
+ })
71
72
 
72
- this.$__molecule.initShadowWalletClaim( {
73
- token,
74
- wallet
75
- } );
76
- this.$__molecule.sign( {} );
77
- this.$__molecule.check();
73
+ this.$__molecule.initShadowWalletClaim(wallet)
74
+ this.$__molecule.sign({})
75
+ this.$__molecule.check()
78
76
  }
79
77
 
80
78
  /**
@@ -83,10 +81,10 @@ export default class MutationClaimShadowWallet extends MutationProposeMolecule {
83
81
  * @param {object} json
84
82
  * @return {ResponseClaimShadowWallet}
85
83
  */
86
- createResponse ( json ) {
87
- return new ResponseClaimShadowWallet( {
84
+ createResponse (json) {
85
+ return new ResponseClaimShadowWallet({
88
86
  query: this,
89
87
  json
90
- } );
88
+ })
91
89
  }
92
90
  }
@@ -45,25 +45,25 @@ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
45
45
 
46
46
  License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
- import MutationProposeMolecule from './MutationProposeMolecule';
49
- import ResponseCreateIdentifier from '../response/ResponseCreateIdentifier';
48
+ import MutationProposeMolecule from './MutationProposeMolecule'
49
+ import ResponseCreateIdentifier from '../response/ResponseCreateIdentifier'
50
50
 
51
51
  /**
52
52
  * Query for creating a new Identifier
53
53
  */
54
54
  export default class MutationCreateIdentifier extends MutationProposeMolecule {
55
- fillMolecule ( {
55
+ fillMolecule ({
56
56
  type,
57
57
  contact,
58
58
  code
59
- } ) {
60
- this.$__molecule.initIdentifierCreation( {
59
+ }) {
60
+ this.$__molecule.initIdentifierCreation({
61
61
  type,
62
62
  contact,
63
63
  code
64
- } );
65
- this.$__molecule.sign( {} );
66
- this.$__molecule.check();
64
+ })
65
+ this.$__molecule.sign({})
66
+ this.$__molecule.check()
67
67
  }
68
68
 
69
69
  /**
@@ -72,11 +72,10 @@ export default class MutationCreateIdentifier extends MutationProposeMolecule {
72
72
  * @param {object} json
73
73
  * @return {ResponseCreateIdentifier}
74
74
  */
75
- createResponse ( json ) {
76
- return new ResponseCreateIdentifier( {
75
+ createResponse (json) {
76
+ return new ResponseCreateIdentifier({
77
77
  query: this,
78
78
  json
79
- } );
79
+ })
80
80
  }
81
-
82
81
  }