Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Created June 11, 2017 19:24
Show Gist options
  • Select an option

  • Save mattmccray/a9f3fc9fa0db9416f3dd4865dea7e900 to your computer and use it in GitHub Desktop.

Select an option

Save mattmccray/a9f3fc9fa0db9416f3dd4865dea7e900 to your computer and use it in GitHub Desktop.
MyJsonAPI TypeScript
class MyJsonAPI<T = any> {
key: string
constructor(key?: string) {
if (validKey(key)) {
this.key = key
}
}
get isReady() {
return validKey(this.key)
}
get apiURL() {
return `${MyJsonAPI.BASE_URL}/${this.key}`
}
get(): Promise<T> {
if (!this.isReady) {
return Promise.reject(new Error(`Invalid key: ${this.key}`))
}
else {
return fetch(this.apiURL).then(toJSON)
}
}
set(value: T): Promise<{ key: string, url: string, data: T }> {
if (!validKey(this.key)) {
return this.create(value)
}
else {
return this.update(value)
}
}
private update(value: T): Promise<{ key: string, url: string, data: T }> {
return fetch(this.apiURL, {
body: value,
method: 'POST',
})
.then(response => {
if (response.ok) {
return ({
key: this.key,
url: this.apiURL,
data: value
})
}
else {
throw new Error(`API Error: ${response.statusText} (${response.status})`)
}
})
}
private create(value: T): Promise<{ key: string, url: string, data: T }> {
return fetch(MyJsonAPI.BASE_URL, {
body: value,
method: 'POST',
})
.then(toJSON)
.then(result => {
const urlParts = result.uri.split('/')
const key = urlParts[urlParts.length - 1]
this.key = key
return { key, url: this.apiURL, data: value }
})
}
static BASE_URL = 'https://api.myjson.com/bins'
}
function validKey(key: string | undefined): key is string {
if (typeof key !== 'string') {
return false
}
else if (key.length === 0) {
return false
}
else {
return true
}
}
function toJSON<T = any>(response: Response): Promise<T> {
return response.json()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment