@cerebral/http
Install
NPM
npm install @cerebral/http
Description
The HTTP provider exposes the ability to do HTTP requests both in actions and directly in signals. It supports cors and file upload, with progress handling. It default to json, but you can configure it to whatever you want.
Read more about http in the Cerebral in depth - Http article.
import {set} from 'cerebral/operators'
import {httpGet} from '@cerebral/http/operators'
import {state, props, string} from 'cerebral/tags'
export default [
httpGet(string`/items/${props`itemKey`}`),
set(state`app.currentItem`, props`result`)
]
All factories of HTTP provider supports template tags.
Instantiate
import {Controller, Module} from 'cerebral'
import HttpProvider from '@cerebral/http'
const http = HttpProvider({
baseUrl: 'https://api.github.com',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json'
},
withCredentials: false,
timeout: 5000
})
const app = Module({
providers: { http }
})
const controller = Controller(app)
You can update these default options in an action:
function updateDefaultHttpOptions({http}) {
http.updateOptions({
})
}
abort
You can abort any running request, causing the request to resolve as status code 0 and sets the type to abort on the error object.
function searchItems({input, state, path, http}) {
http.abort('/items*')
return http.get(`/items?query=${input.query}`)
.then(path.success)
.catch((error) => {
if (error.type === 'abort') {
return path.abort()
}
return path.error({error})
})
}
export default [
searchItems, {
success: [],
error: [],
abort: []
}
]
cors
Cors has been turned into a "black box" by jQuery. Cors is actually a very simple concept, but due to a lot of confusion of "Request not allowed", cors has been an option to help out. In HttpProvider we try to give you the insight to understand how cors actually works.
Cors has nothing to do with the client. The only client configuration related to cors is the withCredentials option, which makes sure cookies are passed to the cross origin server. The only requirement for cors to work is that you pass the correct Content-Type. Now, this depends on the server in question. Some servers allows any content-type, others require a specific one. These are the typical ones:
- text/plain
- application/x-www-form-urlencoded
- application/json; charset=UTF-8
Note that this is only related to the request. If you want to define what you want as response, you set the Accept header, which is application/json by default.
errors
HttpProviderError
import {HttpProviderError} from '@cerebral/http'
{
name: 'HttpProviderError',
type: 'http | abort | timeout',
message: 'Some error message or responseText',
response: {
result: {},
headers: {},
status: 200
},
stack: '...'
}
This error is available in the following scenarios:
function someAction ({http}) {
return http.get('/something').catch(error => ...)
}
[
httpGet('/something'), {
success: [],
error: [
]
}
]
const errorCatched = [
displayError
]
Module({
catch: [
[HttpProviderError, errorCatched]
]
})
delete
action
function someDeleteAction ({http}) {
const query = {}
const options = {}
return http.delete('/items/1', query, options)
.then((response) => {
return {response}
})
.catch((error) => {
return {error}
})
}
operator
import {httpDelete} from '@cerebral/http/operators'
import {state} from 'cerebral/tags'
export default [
httpDelete(string`/items/${state`currentItemId`}`),
]
operator with paths
import {httpDelete} from '@cerebral/http/operators'
import {state} from 'cerebral/tags'
export default [
httpDelete(string`/items/${state`currentItemId`}`), {
success: [
],
error: [
],
abort: [
],
timeout: [
],
'${STATUS_CODE}': [
]
}
]
get
action
function someGetAction ({http}) {
const query = {}
const options = {}
return http.get('/items', query, options)
.then((response) => {
return {someResponse: response}
})
.catch((error) => {
return {someError: error}
})
}
operator
import {httpGet} from '@cerebral/http/operators'
export default [
httpGet('/items'),
]
On error this will throw to the signal or global catch handler.
operator with paths
import {httpGet} from '@cerebral/http/operators'
export default [
httpGet('/items'), {
success: [
],
error: [
],
abort: [
],
timeout: [
],
'${STATUS_CODE}': [
]
}
]
patch
action
function somePatchAction ({http}) {
const data = {}
const options = {}
return http.patch('/items/1', data, options)
.then((response) => {
return {response}
})
.catch((error) => {
return {error}
})
}
operator
import {httpPatch} from '@cerebral/http/operators'
import {state, props, string} from 'cerebral/tags'
export default [
httpPatch(string`/items/${props`itemId`}`, state`patchData`),
]
operator with paths
import {httpPatch} from '@cerebral/http/operators'
import {state, props, string} from 'cerebral/tags'
export default [
httpPatch(string`/items/${props`itemId`}`, state`patchData`), {
success: [
],
error: [
],
abort: [
],
timeout: [
],
'${STATUS_CODE}': [
]
}
]
post
action
function somePostAction ({http}) {
const data = {}
const options = {}
return http.post('/items', data, options)
.then((response) => {
return {response}
})
.catch((error) => {
return {error}
})
}
operator
import {httpPost} from '@cerebral/http/operators'
import {props} from 'cerebral/tags'
export default [
httpPost('/items', {
title: props`itemTitle`,
foo: 'bar'
}),
]
operator with paths
import {httpPost} from '@cerebral/http/operators'
import {props} from 'cerebral/tags'
export default [
httpPost('/items', {
title: props`itemTitle`,
foo: 'bar'
}), {
success: [
],
error: [
],
abort: [
],
timeout: [
],
'${STATUS_CODE}': [
]
}
]
put
action
function somePutAction ({http}) {
const data = {}
const options = {}
return http.put('/items/1', data, options)
.then((response) => {
return {response}
})
.catch((error) => {
return {error}
})
}
operator
import {httpPut} from '@cerebral/http/operators'
export default [
httpPut('/items', {
}),
]
operator with paths
import {httpPut} from '@cerebral/http/operators'
export default [
httpPut('/items', {
}), {
success: [
],
error: [
],
abort: [
],
timeout: [
],
'${STATUS_CODE}': [
]
}
]
responses
There are two types of responses from the HTTP provider. A response and an error of type HttpProviderError. A response will be received on status codes 200-299. Everything else is an error.
response
{
result: 'the response body',
headers: {...},
status: 200
}
error
{
name: 'HttpProviderError',
type: 'http | abort | timeout',
message: 'Some potential error message',
result: 'Message or response body',
status: 500,
headers: {},
stack: '...'
}
request
function someGetAction ({http}) {
return http.request({
method: 'GET',
url: '/items'
body: {},
query: {},
withCredentials: false,
headers: {},
onProgress: null
})
}
uploadFile
action
function someDeleteAction ({http, props}) {
return http.uploadFile('/upload', props.files, {
name: 'filename.png',
data: {},
headers: {},
onProgress: 'some.signal.path'
})
.then((response) => {
return {response}
})
.catch((error) => {
return {error}
})
}
operator
import {httpUploadFile} from '@cerebral/http/operators'
import {state, props} from 'cerebral/tags'
export default [
httpUploadFile('/uploads', props`file`, {
name: state`currentFileName`
}), {
success: [
],
error: [
],
abort: [
],
'${STATUS_CODE}': [
]
}
]
operator with paths
import {httpUploadFile} from '@cerebral/http/operators'
import {state, props} from 'cerebral/tags'
export default [
httpUploadFile('/uploads', props`file`, {
name: state`currentFileName`
}),
]