Created
April 15, 2019 19:29
-
-
Save canterberry/53b44bd313cc8d25674c0458fd754f75 to your computer and use it in GitHub Desktop.
A minimal JavaScript SDK for interacting with Blockmason Link.
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 link = (options = {}) => { | |
const { | |
baseUrl = 'https://api.block.mason.link', | |
clientId, | |
clientSecret | |
} = options; | |
if (!clientId || !clientSecret) { | |
throw new Error('Missing options.clientId or options.clientSecret'); | |
} | |
const toQueryString = (inputs = {}) => { | |
const pairs = []; | |
const keys = Object.keys(inputs); | |
for (const key of keys) { | |
const { [key]: value } = inputs; | |
pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); | |
} | |
if (pairs.length > 0) { | |
return `?${pairs.join('&')}`; | |
} | |
return ''; | |
}; | |
const credential = {}; | |
const authenticate = async () => { | |
if (credential.accessToken) { | |
return Promise.resolve(credential.accessToken); | |
} | |
const response = await fetch(`${baseUrl}/oauth2/token`, { | |
body: JSON.stringify(credential.refreshToken ? { | |
grant_type: 'refresh_token', | |
refresh_token: credential.refreshToken | |
} : { | |
client_id: clientId, | |
client_secret: clientSecret, | |
grant_type: 'client_credentials' | |
}), | |
headers: { 'Content-Type': 'application/json' }, | |
method: 'POST' | |
}); | |
const { access_token, errors, refresh_token } = await response.json(); | |
if (errors && errors.length > 0) { | |
throw new Error(errors.map((error) => error.detail).join(' ')); | |
} | |
Object.assign(credential, { accessToken: access_token, refreshToken: refresh_token }); | |
return credential.accessToken; | |
}; | |
return { | |
get: async (path = '/', inputs = {}) => { | |
const accessToken = await authenticate(); | |
const response = await fetch(`${baseUrl}/v1${path}${toQueryString(inputs)}`, { headers: { Authorization: `Bearer ${accessToken}` }, method: 'GET' }); | |
const outputs = await response.json(); | |
return outputs; | |
}, | |
post: async (path = '/', inputs = {}) => { | |
const accessToken = await authenticate(); | |
const response = await fetch(`${baseUrl}/v1${path}`, { | |
body: JSON.stringify(inputs), | |
headers: { | |
Authorization: `Bearer ${accessToken}`, | |
'Content-Type': 'application/json' | |
}, | |
method: 'POST' | |
}); | |
const outputs = await response.json(); | |
return outputs; | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: