0.0.6 • Published 7 years ago

cans-plugin-http v0.0.6

Weekly downloads
18
License
-
Repository
-
Last release
7 years ago

cans-plugin-http

npm circle

HTTP (axios) plugin for cans

Install

$ yarn add cans-plugin-http

Usage

httpPlugin

Example

import cans from 'cans'
import { observable, action } from 'cans/mobx'
import { httpPlugin } from 'cans-plugin-http'

const app = cans()

app.use(httpPlugin)

app.model({
  observable: app => {
    return observable({
      list: [],

      fetchList: action.bound(async function () {
        const list = (await app.http.get('/api/v1/lists')).data
        // modify `list`
      })
    })
  }
})

options

  • axiosConfig: AxiosConfig. If provided, app.http will return axios.create(axiosConfig)

restPlugin

restPlugin is useful when your backend exposed frontend a standard RESTful interface. restPlugin will help you generate RESTful cans model that return a observable, which contains RESTful action and loading status:

MethodPathaction
GET/postsapp.models.rest.posts.index
GET/posts/:idapp.models.rest.posts.show
POST/postsapp.models.rest.posts.create
PUT/posts/:idapp.models.rest.posts.update
DELETE/posts/:idapp.models.rest.posts.delete

(Inspired by Egg)

Example

import cans from 'cans'
import { observable, action } from 'cans/mobx'
import { restPlugin } from 'cans-plugin-http'

const app = cans()

const URL = 'http://jsonplaceholder.typicode.com'

app.use(restPlugin, { 
  resources: [
    { name: 'posts', url: URL }
  ]
})

const PostList = ({ posts }) => (
  <div>
    {posts.map(post => (
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    ))}
  </div>
)

const PostApp = inject(({ models }) => (
  <div>
    <button disable={models.rest.posts.loading.index} onClick={models.rest.posts.index}>Fetch</button>
    <PostList posts={models.rest.posts.data.index} />
  </div>
))

options

  • resources

    • name: resource name
    • url: endpoint URL
    • total: (AxiosResponse) => string | number - Compute total count from response
    • defaultData: { index: any, show: any } - Data fetched from rest[name].index will be set in rest[name].data.index. show is the same. index is [] by default. show is {} by default.

What in app.models.rest[name]

restPlugin create observables for every resource:

observable({
  // data fetched from RESTful interface
  data: {
    index: defaultData.index || [],
    show: defaultData.show || {}
  },
  // loading status
  loading: {
    index: boolean,
    show: boolean,
    create: boolean,
    update: boolean,
    delete: boolean
  },

  // action
  async index(),
  async show(id),
  async create(data),
  async update(id, data),
  async delete(id)
})

License

MIT License

0.0.6

7 years ago

0.0.5

7 years ago

0.0.4

7 years ago

0.0.3

7 years ago

0.0.2

7 years ago

0.0.1

7 years ago