Skip to content

Instantly share code, notes, and snippets.

@zahedkamal87
Forked from laosb/jsonBinApi.js
Created April 23, 2022 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zahedkamal87/a741c4bb0b1a48c847e13c41e39b894c to your computer and use it in GitHub Desktop.
Save zahedkamal87/a741c4bb0b1a48c847e13c41e39b894c to your computer and use it in GitHub Desktop.
Simple API wrapper for JSONBin.io.
import fetch from 'node-fetch'
const secretKey = process.env.JSONBIN_SECRET_KEY
const basicHeaders = () => ({
'Content-Type': 'application/json',
'X-Master-Key': secretKey,
})
export const createBin = async (
name,
collectionId,
content,
isPrivate = true
) => {
const headers = {
...basicHeaders(),
...(isPrivate ? {} : { 'X-Bin-Private': 'false' }),
'X-Bin-Name': name,
'X-Collection-Id': collectionId,
}
const result = await fetch('https://api.jsonbin.io/v3/b', {
method: 'post',
body: JSON.stringify(content),
headers,
})
if (!result.ok) throw new Error('createBin Error: ' + (await result.text()))
return await result.json()
}
export const readBin = async (id, version = 'latest') => {
const result = await fetch(`https://api.jsonbin.io/v3/b/${id}/${version}`, {
headers: basicHeaders(),
})
if (!result.ok) throw new Error('readBin Error: ' + (await result.text()))
return await result.json()
}
export const updateBin = async (id, content, shouldDoVersioning = true) => {
const headers = {
...basicHeaders(),
'X-Bin-Versioning': shouldDoVersioning ? 'true' : 'false',
}
const result = await fetch(`https://api.jsonbin.io/v3/b/${id}`, {
method: 'put',
body: JSON.stringify(content),
headers,
})
if (!result.ok) throw new Error('updateBin Error: ' + (await result.text()))
return await result.json()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment