syncher-api
v0.0.22
Published
extended fetch api with synch and auth apis
Maintainers
Readme
AJAXNESS
Ajaxness contains an extended fetch API with SWR caching extensions. It also contains a specialized Synch API for RESTful CRUD and a minimalist Auth API for bearer authentication with JWT and oAuth.
fetch API
Extended fetch api with SWR settings features (caching, retry, etc).
import { fetch } from 'react-'
// swr caching support
const cache = 42000
const cacheKeys = ['todos', 'ok']
fetch(url, { cache })
fetch(url, { cache: "7min" })
fetch(url, { cache, cacheKeys })
fetch(url, { cache: "no-cache" })
fetch(url, { cache: "force-cache" })
// revalidate (clear cache)
fetch.clear(cacheKeys)
fetch.clear() // all// swr features
const callback = e => console.log(e)
const retry = { repeat:3, interval:1000 }
const reget = { interval:1000, callback }
await fetch("http://etc.com", { retry })
await fetch("http://etc.com", { reget })
// auth token state
fetch.token = `Bearer ${token}`
// easy interceptors
fetch.on("request", req => ...)
fetch.on("response", res => ...)
fetch.on("exception", err => ...)Synch API
RESTful fluent API for synchornization semantics.
import { syncher } from 'react-'
const messageApi = syncher<User>(true)
.fetch("http://message.api/baseURL")
.catch(e => "not found...")
.match(x => x, "id")
// message Api is a ISync type
interface ISync<T,E> {
value: T
await: boolean
error: E|undefined
async(mutate?): Promise<void>
}// sync search/mutate flag
sync() // querying sync
sync(true) // mutation sync
// support SWR methods
const messageApi = syncher<User>(true)
.retry(3, 1000)
.cache(1000, ["messages", 1])
.reget(1000, x => "pooling...")
.fetch("http://message.api/baseURL")
.catch(e => "not found...")
.match(x => x, "id") Auth API
Simple fluent authentication API for JWT Bearer and oAuth authentication.
import { auth } from 'ajaxness'
// JWT bearer + basic Auth
interface Token { access: string }
interface User { role: string }
const session = auth<User>(false)
.fetch("http://www.google.com/login")
.catch("/login", "Login fails")
.match<Token>("/home", x => x.token)
// oAuth provider support
const googleAuth = {
scopings: ['profile', 'email'],
clientId: 'asdfasfsadfasdfasdf.apps.googleusercontent.com',
queryURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
tokenURL: 'https://accounts.google.com/o/oauth2/auth'
}
const session = auth(true, googleAuth)
.catch('/index.html', 'failed login...')
.match('/poc/home.html', x => x.access_token)
// login and logout behavior
await session.login(username, password)
const user = session.logged
session.logout()