Created
August 4, 2020 17:13
-
-
Save GavinRay97/3a8f9a8d3b29b9bc0f8e9cfb68a5725d to your computer and use it in GitHub Desktop.
GraphQL Tx over Websocket SDK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const WebSocket = require('ws') | |
const WebSocketAsPromised = require('websocket-as-promised') | |
// SDK Code | |
const socketFactory = (url) => | |
new WebSocket(url, 'graphql-tx', { | |
headers: { | |
'X-Hasura-Tx-Isolation': 'serializable', | |
}, | |
}) | |
const socket = new WebSocketAsPromised('ws://localhost:8080/v1/graphql', { | |
createWebSocket: (url) => socketFactory(url), | |
extractMessageData: (event) => event, | |
packMessage: (data) => data, | |
unpackMessage: (data) => JSON.parse(data as string), | |
attachRequestId: (data, requestId) => data, | |
extractRequestId: (data) => data && data.request_id, | |
}) | |
const txns = { | |
init: JSON.stringify({ | |
type: 'init', | |
payload: { | |
isolation: 'serializable', | |
}, | |
}), | |
abort: JSON.stringify({ | |
type: 'abort', | |
}), | |
commit: JSON.stringify({ | |
type: 'commit', | |
}), | |
sendQuery: (query) => | |
JSON.stringify({ | |
type: 'execute', | |
payload: { | |
query: { | |
query: query, | |
}, | |
}, | |
}), | |
} | |
socket.onResponse.addListener((data, requestId) => { | |
console.log('response data:', data) | |
const reqPromise = socket._requests._items.get('req') | |
reqPromise.resolve(data) | |
}) | |
socket.onMessage.addListener((data) => console.log('data:', data)) | |
socket.onSend.addListener((...data) => console.log('sent', data)) | |
const transaction = (query) => { | |
let result | |
return socket | |
.open() | |
.then(() => socket.send(txns.init)) | |
.then(() => | |
socket.sendRequest(txns.sendQuery(query), { requestId: 'req' }) | |
) | |
.then((response) => { | |
result = response | |
socket.send(txns.commit) | |
}) | |
.then(() => { | |
console.log('Committed transaction, got result:', result) | |
return result | |
}) | |
.catch((err) => { | |
socket.send(txns.abort) | |
console.log('Error:', err) | |
}) | |
} | |
// Demo code | |
const getUserQuery = 'query q { users { id name} }' | |
transaction(getUserQuery).then((res) => { | |
console.log('Transaction finished with response', res) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment