@apicase/fluent
Fluent interface for Apicase services
Benefits
- Like Apicase and unlike another solutions, it's not API-specific
- Highly customizable. You can easily add your own methods and even whole schemas (based on schematic-fluent)
- Fluent instance is immutable and don't modify current instance but returns the new one
Installation
npm i @apicase/fluent
npm i @apicase/adapter-fetch
Usage guide
Create fluent Apicase service
import fetchSchema from "@apicase/fluent/fetch"
import fluentApicase from "@apicase/fluent"
import { ApiService } from "@apicase/services"
const FluentFetch = fluentApicase(fetchSchema).service(new ApiService())
FluentFetch.get("/photos")
.query("foo", "bar")
.doRequest()
.then(console.log)
Service methods
All ApiService
methods are available in fluent interface:
FluentFetch.doRequest()
FluentFetch.pushRequest()
FluentFetch.doSingleRequest()
FluentFetch.doUniqueRequest()
Also, there are additional methods
FluentFetch.getPayload()
FluentFetch.getService()
Add hooks or events
const addToken = ({ payload, next }) => {
payload.headers = payload.headers || {}
payload.headers.token = localStorage.token
next(payload)
}
const WithAuth = FluentFetch.on("done", console.log).hook("before", addToken)
Available methods
apicaseFluent()
methods
apicaseFluent
function just extends schema with the following methods:
Root
.adapter(SomeAdapter)
.service(SomeService)
.meta('foo', 'bar')
.meta({ foo: 'bar' })
.on('evtName', cb)
.hook('hookType', cb)
.hooks({
done: cb,
fail: cb
})
fetchSchema
methods
To reduce boilerplate code, we provide ready-to-use schema for fetch adapter.
Fetch schema has the following methods:
Root
.get("/photos/:id")
.post("/photos")
.put("/photos/:id")
.patch("/photos/:id")
.delete("/photos/:id")
.url("/foo/bar")
.method("GET")
.query("foo", "bar")
.query({ foo: "bar" })
.param("id", 1)
.param({ id: 1 })
.header("token", "12345")
.header({ token: "12345" })
.body("something")
.body(new FormData())
.body({ foo: "bar" })
Customization
We use schematic-fluent for schemas.
You can check out its README for more info
Extend schema or instance
import fetchSchema from "@apicase/fluent/fetch"
import apicaseFluent from "@apicase/fluent"
const jsonApiSchema = fetchSchema.extend({
methods: {
include: (ctx, { method }) => include =>
method("query", { include }),
page: (ctx, { method }) => (number, limit) =>
method("query", { page: { number, limit } })
}
})
const Root = apicaseFluent(jsonApiSchema)
const GetPost = Root
.get('/post')
.extend({
method: {
id: (ctx, { method }) => id => method('param', id)
}
})
GetPost
.include(['author'])
.id(1)
.doRequest()
.then(console.log)
Use your own schema
Docs coming soon...