@5rabbits/mobx-rest 中文文档教程
mobx-rest
mobx 的 REST 约定。
Table of Contents
- Installation
- What is it?
- Full React example
- Documentation
- Model
- Collection
- apiClient
- Simple Example
- State shape
- FAQ
- Where is it used?
- License
Installation
npm install mobx-rest --save
What is it?
一个应用程序状态通常分为三个领域:
- Component state: Each state can have their own state, like a button being pressed, a text input value, etc.
- Application state: Sometimes we need components to share state between them and they are too far away to actually make them talk each other through props.
- Resources state: Other times, state is persisted in the server. We synchronize that state through APIs that consume resources. One way to synchronize this state is through REST.
MobX 是处理这三个领域的绝佳状态管理选择: 它允许您将状态表示为图表,而其他解决方案, 例如像 Redux,强制你将你的状态表示为一棵树。
使用 mobx-rest
资源是用它们所有的 REST 实现的 内置操作(create
, fetch
, save
, destroy
, ...) 一遍又一遍地编写数百行我们可以利用的样板 REST 约定可最大程度地减少 API 交互所需的代码。
Full React example
如果你想看一个完整的 React 例子,你 可以查看 mobx-rest-example repo。 该演示部署在此处。
Documentation
mobx-rest
相当简单,5 分钟即可阅读其源代码。
Model
一个 Model
代表一个资源。 它由主键(强制)标识并保存 它的属性。 您可以在客户端创建、更新和销毁模型,然后同步 他们与服务器。 除了它的属性,Model
还保存了状态 与服务器的交互,以便您可以轻松地对这些做出反应(显示加载状态 例如)。
constructor(attributes: Object)
使用给定的属性初始化模型。
您还可以覆盖它以提供默认属性,如下所示:
class User extends Model {
constructor(attributes) {
super(Object.assign({
token: null,
email_verified: false,
}, attributes))
}
}
attributes: ObservableMap
一个包含模型属性的 ObservableMap
。
collection: ?Collection
指向 Collection
的指针。 通过拥有模型 “属于”一个你可以拿出最多的收藏 mobx-rest
的。
request
一个 Request
对象,表示正在进行的请求的状态(如果有)。
error
表示失败请求状态的 Error
对象(如果有)。
toJS(): Object
返回属性的对象版本。
primaryKey: string
实现这个抽象方法,让 mobx-rest
知道要做什么 用作主键。 它默认为 'id'
但如果您使用 像 mongodb 这样的东西,你可以把它改成 '_id'
。
urlRoot(): string
实现这个抽象方法让 mobx-rest
知道在哪里 它的 API 指向。 如果模型属于 Collection
(设置 collection
属性)这个方法做 不需要实施。
url(): string
返回给定资源的 url。 将利用 集合的基本 url(如果有)或 urlRoot
。 它使用 主要 ID,因为这是 REST 约定。
示例:<代码>tasks.get(34).url() // => "/tasks/34"
isRequest(label: string): boolean
询问模型是否正在进行的辅助方法 带有给定标签的请求。
示例:file.isRequest('saving')
isNew: boolean
返回该模型是否已与服务器同步。 在客户端(乐观地)创建的资源没有 id
属性(由服务器提供)
示例:
const user = new User({ name : 'Pau' })
user.isNew // => true
user.save()
user.isNew // => false
user.get('id') // => 1
get(attribute: string): any
获取给定的属性。 如果该属性不存在,则会抛出错误。
如果不同的资源有不同的模式,你可以 始终使用 has
来检查给定属性是否存在。
示例:
if (user.has('role')) {
return user.get('role')
} else {
return 'basic'
}
has(attribute: string): boolean
检查给定的属性是否存在。
set(data: Object): void
更新客户端中的属性。
示例:
const folder = new Folder({ name : 'Trash' })
folder.get('name') // => 'Trash'
folder.set({ name: 'Rubbish' })
folder.get('name') // => 'Rubbish'
fetch(options): Promise
从服务器请求此资源的数据。 它跟踪状态 使用标签 fetching
的请求,并在以下时间更新资源 数据从 API 返回。
示例:
const task = new Task({ id: 3 })
const promise = task.fetch()
task.isRequest('fetching') // => true
await promise
task.get('name') // => 'Do the laundry'
save(attributes: Object, options: Object): Promise
与 fetch
相反。 它从客户端获取资源并 通过 API 将其保存在服务器中。 它接受一些属性 作为第一个参数,因此您可以将其用作 set
+ save
。 它使用标签 saving
跟踪请求的状态。
选项:
optimistic = true
Whether we want to update the resource in the client first or wait for the server's response.patch = true
Whether we want to use thePATCH
verb and semantics, sending only the changed attributes instead of the whole resource down the wire.
示例:
const company = new Company({ name: 'Teambox' })
const promise = company.save({ name: 'Redbooth' }, { optimistic: false })
company.isRequest('saving') // => true
company.get('name') // => 'Teambox'
await promise
company.get('name') // => 'Redbooth'
destroy(options: Object): Promise
告诉 API 销毁此资源。
选项:
optimistic = true
Whether we want to delete the resource in the client first or wait for the server's response.
rpc(method: 'string', body: {}): Promise
在处理 REST 时,总有一些情况是我们有一些超出范围的操作 公约。 这些被表示为 rpc
调用并且没有固执己见。
示例:
const response = await task.rpc('resolveSubtasks', { all: true })
if (response.ok) {
task.subTasks.fetch()
}
Collection
Collection
表示一组资源。 Collection
的每个元素都是一个Model
。 同样,集合也会跟踪与服务器交互的状态,因此您 可以做出相应的反应。
models: ObservableArray
保存模型集合的 ObservableArray
。
request: ?Request
一个 Request
对象,表示正在进行的请求的状态(如果有)。
error: ?ErrorObject
表示失败请求状态的 Error
对象(如果有)。
constructor(data: Array<Object>)
使用给定的资源初始化集合。
url(): string
如果你想要你的集合,必须实现的抽象方法 它是能够与 API 交互的模型。
model(): Model
抽象方法,告诉该集合是哪种 Model
对象 持有。 例如,在执行 collection.create
时会用到它 我们知道要实例化哪个对象。
toJS(): Array<Object>
返回表示资源集合的普通数据结构 没有所有可观察层。
toArray(): Array<ObservableMap>
返回包含可观察资源的数组。
isRequest(label: string): boolean
询问集合是否有正在进行的帮助程序方法 带有给定标签的请求。
示例:
filesCollection.isRequest('saving')
isEmpty(): boolean
询问集合是否存在的辅助方法 其中的模型。
示例:
const promise = usersCollection.fetch()
usersCollection.isEmpty() // => true
await promise
usersCollection.isEmpty() // => false
usersCollection.models.length // => 10
at(index: number): ?Model
在给定位置查找模型。
get(id: number): ?Model
查找(或不查找)具有给定 ID 的模型。
filter(query: Object): Array<Model>
按给定条件表示的过滤集合的辅助方法 作为键值。
示例:
const resolvedTasks = tasksCollection.filter({ resolved: true })
resolvedTasks.length // => 3
find(query: Object): ?Model
与 filter
相同,但它会在第一个模型匹配时停止并返回 条件。
示例:
const pau = usersCollection.find({ name: 'pau' })
pau.get('name') // => 'pau'
add(data: Array<Object>): Array<Model>
添加具有给定属性数组的模型。
usersCollection.add([{id: 1, name: 'foo'}])
reset(data: Array<Object>): Array<Model>
用给定的模型重置集合。
usersCollection.reset([{id: 1, name: 'foo'}])
remove(ids: Array<number>): void
删除具有给定 ID 的任何模型。
示例:
usersCollection.remove([1, 2, 3])
set(models: Array<Object>, options: Object): void
巧妙地将给定模型合并为集合中的当前模型。 它检测要添加、删除和更改的内容。
选项:
add = true
Change to disable adding modelschange = true
Change to disable updating modelsremove = true
Change to disable removing models
const companiesCollection = new CompaniesCollection([
{ id: 1, name: 'Teambox' }
{ id: 3, name: 'Zpeaker' }
])
companiesCollection.set([
{ id: 1, name: 'Redbooth' },
{ id: 2, name: 'Factorial' }
])
companiesCollection.get(1).get('name') // => 'Redbooth'
companiesCollection.get(2).get('name') // => 'Factorial'
companiesCollection.get(3) // => null
build(attributes: Object): Model
实例化模型并将其链接到当前集合。
const factorial = companiesCollection.build({ name: 'Factorial' })
factorial.collection === companiesCollection // => true
factorial.get('name') // 'Factorial'
create(target: Object | Model, options: Object)
添加并保存给定模型的服务器。 如果给出属性, 它还为您构建模型。 它跟踪请求的状态 使用标签 creating
。
选项:
optimistic = true
Whether we want to create the resource in the client first or wait for the server's response.
const promise = tasksCollection.create({ name: 'Do laundry' })
tasksCollection.isRequest('creating') // => true
await promise
tasksCollection.at(0).get('name') // => 'Do laundry'
fetch(options: Object)
从服务器获取日期,然后调用 set
更新当前 楷模。 接受来自 set
方法的任何选项。
const promise = tasksCollection.fetch()
tasksCollection.isEmpty() // => true
tasksCollection.isRequest('fetching') // => true
await promise
tasksCollection.isEmpty() // => false
rpc(method: 'string', body: {}): Promise
与模型一完全相同,但在收藏级别。
apiClient
这是将发出 xhr
请求以与您的 API 交互的对象。 目前有两种实现方式:
- One using
jQuery
in the mobx-rest-jquery-adapter package. - One using
fetch
in the mobx-rest-fetch-adapter package.
首先,您需要使用适配器和 apiPath
配置 apiClient()
。 您还可以设置其他选项,例如与所有请求一起发送的标头。
例如,如果您使用 JWT 并需要使用 Authorization 标头发送它,它可能如下所示:
const options = {
apiPath: window.env.apiUrl,
}
if (token) {
options.commonOptions = {
headers: {
Authorization: `Bearer ${token}`
}
}
}
apiClient(adapter, options)
所有选项:
- apiPath (required): what do prepend for all model and collections URLs
- commonOptions: settings to use for all requests
- headers: Additional request headers, like
Authorization
- tbd.
Simple Example
一个集合如下所示:
// TasksCollection.js
const apiPath = '/api'
import adapter from 'mobx-rest-fetch-adapter'
import { apiClient, Collection, Model } from 'mobx-rest'
// We will use the adapter to make the `xhr` calls
apiClient(adapter, { apiPath })
class Task extends Model { }
class Tasks extends Collection {
url () { return `/tasks` }
model () { return Task }
}
// We instantiate the collection and export it as a singleton
export default new Tasks()
这里是如何使用 React 的示例:
import tasksCollection from './TasksCollection'
import { computed } from 'mobx'
import { observer } from 'mobx-react'
@observer
class Task extends React.Component {
onClick () {
this.props.task.save({ resolved: true })
}
render () {
return (
<li key={task.id}>
<button onClick={this.onClick.bind(this)}>
resolve
</button>
{this.props.task.get('name')}
</li>
)
}
}
@observer
class Tasks extends React.Component {
componentWillMount () {
// This will call `/api/tasks?all=true`
tasksCollection.fetch({ data: { all: true } })
}
@computed
get activeTasks () {
return tasksCollection.filter({ resolved: false })
}
render () {
if (tasksCollection.isRequest('fetching')) {
return <span>Fetching tasks...</span>
}
return (
<div>
<span>{this.activeTasks.length} tasks</span>
<ul>{activeTasks.map((task) => <Task task={task} />)}</ul>
</div>
)
}
}
State shape
您的集合和模型将具有以下状态形状:
Collection
models: Array<Model> // This is where the models live
request: { // An ongoing request
label: string, // Examples: 'updating', 'creating', 'fetching', 'destroying' ...
abort: () => void, // A method to abort the ongoing request
progress: number // If uploading a file, represents the progress
},
error: { // A failed request
label: string, // Examples: 'updating', 'creating', 'fetching', 'destroying' ...
body: Object, // A string representing the error
}
Model
attributes: Object // The resource attributes
optimisticId: string, // Client side id. Used for optimistic updates
request: { // An ongoing request
label: string, // Examples: 'updating', 'creating', 'fetching', 'destroying' ...
abort: () => void, // A method to abort the ongoing request
},
error: { // A failed request
label: string, // Examples: 'updating', 'creating', 'fetching', 'destroying' ...
body: string, // A string representing the error
},
FAQ
How do I create relations between the models?
这是 mobx 非常容易实现的东西:
import usersCollection from './UsersCollections'
import { computed } from 'mobx'
class Task extends Model {
@computed
author () {
const userId = this.get('userId')
return usersCollection.get(userId) ||
usersCollection.nullObject()
}
}
我建议始终使用 null 对象进行回退,这将有助于 大量编写类似 task.author.get('name')
的代码。
Where is it used?
License
(麻省理工学院许可证)
中开发并在生产中进行战斗测试版权所有 (c) 2017 Pau Ramon masylum@gmail.com
特此免费授予获得本软件和相关文档文件(“软件”)副本的任何人不受限制地处理本软件的权限,包括无限制使用、复制、修改、合并、发布、分发、再许可和/或出售软件副本的权利,并允许软件的接收人这样做,但须满足以下条件:
上述版权通知和本许可通知应包含在软件的所有副本或重要部分中。
本软件“按原样”提供,不提供任何明示或暗示的保证,包括但不限于对适销性、特定用途的适用性和非侵权性的保证。 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是在合同诉讼、侵权行为还是其他方面,由软件或软件的使用或其他交易引起、由软件引起或与之相关软件。
mobx-rest
REST conventions for mobx.
Table of Contents
- Installation
- What is it?
- Full React example
- Documentation
- Model
- Collection
- apiClient
- Simple Example
- State shape
- FAQ
- Where is it used?
- License
Installation
npm install mobx-rest --save
What is it?
An application state is usually divided into three realms:
- Component state: Each state can have their own state, like a button being pressed, a text input value, etc.
- Application state: Sometimes we need components to share state between them and they are too far away to actually make them talk each other through props.
- Resources state: Other times, state is persisted in the server. We synchronize that state through APIs that consume resources. One way to synchronize this state is through REST.
MobX is an excellent state management choice to deal with those three realms: It allows you to represent your state as a graph while other solutions, like Redux for instance, force you to represent your state as a tree.
With mobx-rest
resources are implemented with all their REST actions built in (create
, fetch
, save
, destroy
, …) so instead of writing, over and over, hundreds of lines of boilerplate we can leverage REST conventions to minimize the code needed for your API interactions.
Full React example
If you want to see a full example with React you can check out the mobx-rest-example repo. The demo is deployed here.
Documentation
mobx-rest
is fairly simple and its source code could be read in 5 minutes.
Model
A Model
represents one resource. It's identified by a primary key (mandatory) and holds its attributes. You can create, update and destroy models in the client and then sync them with the server. Apart from its attributes, a Model
also holds the state of the interactions with the server so you can react to those easily (showing loading states for instance).
constructor(attributes: Object)
Initialize the model with the given attributes.
You can also overwrite it to provide default attributes like this:
class User extends Model {
constructor(attributes) {
super(Object.assign({
token: null,
email_verified: false,
}, attributes))
}
}
attributes: ObservableMap
An ObservableMap
that holds the attributes of the model.
collection: ?Collection
A pointer to a Collection
. By having models "belong to" a collection you can take the most out of mobx-rest
.
request
A Request
object that represents the state of the ongoing request, if any.
error
An Error
object that represents the state of the failed request, if any.
toJS(): Object
Return the object version of the attributes.
primaryKey: string
Implement this abstract method so mobx-rest
knows what to use as a primary key. It defaults to 'id'
but if you use something like mongodb you can change it to '_id'
.
urlRoot(): string
Implement this abstract method so mobx-rest
knows where its API points to. If the model belongs to a Collection
(setting the collection
attribute) this method does not need to be implemented.
url(): string
Return the url for that given resource. Will leverage the collection's base url (if any) or urlRoot
. It uses the primary id since that's REST convention.
Example: tasks.get(34).url() // => "/tasks/34"
isRequest(label: string): boolean
Helper method that asks the model whether there is an ongoing request with the given label.
Example: file.isRequest('saving')
isNew: boolean
Return whether that model has been synchronized with the server or not. Resources created in the client side (optimistically) don't have an id
attribute yet (that's given by the server)
Example:
const user = new User({ name : 'Pau' })
user.isNew // => true
user.save()
user.isNew // => false
user.get('id') // => 1
get(attribute: string): any
Get the given attribute. If the attribute does not exist, it will throw an error.
If different resources have different schemas you can always use has
to check whether a given attribute exists or not.
Example:
if (user.has('role')) {
return user.get('role')
} else {
return 'basic'
}
has(attribute: string): boolean
Check that the given attribute exists.
set(data: Object): void
Update the attributes in the client.
Example:
const folder = new Folder({ name : 'Trash' })
folder.get('name') // => 'Trash'
folder.set({ name: 'Rubbish' })
folder.get('name') // => 'Rubbish'
fetch(options): Promise
Request this resource's data from the server. It tracks the state of the request using the label fetching
and updates the resource when the data is back from the API.
Example:
const task = new Task({ id: 3 })
const promise = task.fetch()
task.isRequest('fetching') // => true
await promise
task.get('name') // => 'Do the laundry'
save(attributes: Object, options: Object): Promise
The opposite of fetch
. It takes the resource from the client and persists it in the server through the API. It accepts some attributes as the first argument so you can use it as a set
+ save
. It tracks the state of the request using the label saving
.
Options:
optimistic = true
Whether we want to update the resource in the client first or wait for the server's response.patch = true
Whether we want to use thePATCH
verb and semantics, sending only the changed attributes instead of the whole resource down the wire.
Example:
const company = new Company({ name: 'Teambox' })
const promise = company.save({ name: 'Redbooth' }, { optimistic: false })
company.isRequest('saving') // => true
company.get('name') // => 'Teambox'
await promise
company.get('name') // => 'Redbooth'
destroy(options: Object): Promise
Tells the API to destroy this resource.
Options:
optimistic = true
Whether we want to delete the resource in the client first or wait for the server's response.
rpc(method: 'string', body: {}): Promise
When dealing with REST there are always cases when we have some actions beyond the conventions. Those are represented as rpc
calls and are not opinionated.
Example:
const response = await task.rpc('resolveSubtasks', { all: true })
if (response.ok) {
task.subTasks.fetch()
}
Collection
A Collection
represents a group of resources. Each element of a Collection
is a Model
. Likewise, a collection tracks also the state of the interactions with the server so you can react accordingly.
models: ObservableArray
An ObservableArray
that holds the collection of models.
request: ?Request
A Request
object that represents the state of the ongoing request, if any.
error: ?ErrorObject
An Error
object that represents the state of the failed request, if any.
constructor(data: Array<Object>)
Initializes the collection with the given resources.
url(): string
Abstract method that must be implemented if you want your collection and it's models to be able to interact with the API.
model(): Model
Abstract method that tells which kind of Model
objects this collection holds. This is used, for instance, when doing a collection.create
so we know which object to instantiate.
toJS(): Array<Object>
Return a plain data structure representing the collection of resources without all the observable layer.
toArray(): Array<ObservableMap>
Return an array with the observable resources.
isRequest(label: string): boolean
Helper method that asks the collection whether there is an ongoing request with the given label.
Example:
filesCollection.isRequest('saving')
isEmpty(): boolean
Helper method that asks the collection whether there is any model in it.
Example:
const promise = usersCollection.fetch()
usersCollection.isEmpty() // => true
await promise
usersCollection.isEmpty() // => false
usersCollection.models.length // => 10
at(index: number): ?Model
Find a model at the given position.
get(id: number): ?Model
Find a model (or not) with the given id.
filter(query: Object): Array<Model>
Helper method that filters the collection by the given conditions represented as a key value.
Example:
const resolvedTasks = tasksCollection.filter({ resolved: true })
resolvedTasks.length // => 3
find(query: Object): ?Model
Same as filter
but it will halt and return when the first model matches the conditions.
Example:
const pau = usersCollection.find({ name: 'pau' })
pau.get('name') // => 'pau'
add(data: Array<Object>): Array<Model>
Adds models with the given array of attributes.
usersCollection.add([{id: 1, name: 'foo'}])
reset(data: Array<Object>): Array<Model>
Resets the collection with the given models.
usersCollection.reset([{id: 1, name: 'foo'}])
remove(ids: Array<number>): void
Remove any model with the given ids.
Example:
usersCollection.remove([1, 2, 3])
set(models: Array<Object>, options: Object): void
Merge the given models smartly the current ones in the collection. It detects what to add, remove and change.
Options:
add = true
Change to disable adding modelschange = true
Change to disable updating modelsremove = true
Change to disable removing models
const companiesCollection = new CompaniesCollection([
{ id: 1, name: 'Teambox' }
{ id: 3, name: 'Zpeaker' }
])
companiesCollection.set([
{ id: 1, name: 'Redbooth' },
{ id: 2, name: 'Factorial' }
])
companiesCollection.get(1).get('name') // => 'Redbooth'
companiesCollection.get(2).get('name') // => 'Factorial'
companiesCollection.get(3) // => null
build(attributes: Object): Model
Instantiates and links a model to the current collection.
const factorial = companiesCollection.build({ name: 'Factorial' })
factorial.collection === companiesCollection // => true
factorial.get('name') // 'Factorial'
create(target: Object | Model, options: Object)
Add and save to the server the given model. If attributes are given, also it builds the model for you. It tracks the state of the request using the label creating
.
Options:
optimistic = true
Whether we want to create the resource in the client first or wait for the server's response.
const promise = tasksCollection.create({ name: 'Do laundry' })
tasksCollection.isRequest('creating') // => true
await promise
tasksCollection.at(0).get('name') // => 'Do laundry'
fetch(options: Object)
Fetch the date from the server and then calls set
to update the current models. Accepts any option from the set
method.
const promise = tasksCollection.fetch()
tasksCollection.isEmpty() // => true
tasksCollection.isRequest('fetching') // => true
await promise
tasksCollection.isEmpty() // => false
rpc(method: 'string', body: {}): Promise
Exactly the same as the model one, but at the collection level.
apiClient
This is the object that is going to make the xhr
requests to interact with your API. There are currently two implementations:
- One using
jQuery
in the mobx-rest-jquery-adapter package. - One using
fetch
in the mobx-rest-fetch-adapter package.
Initially you need to configure apiClient()
with an adapter and the apiPath
. You can also set additional options, like headers to send with all requests.
For example, if you're using JWT and need to send it using the Authorization header, it could look like this:
const options = {
apiPath: window.env.apiUrl,
}
if (token) {
options.commonOptions = {
headers: {
Authorization: `Bearer ${token}`
}
}
}
apiClient(adapter, options)
All options:
- apiPath (required): what do prepend for all model and collections URLs
- commonOptions: settings to use for all requests
- headers: Additional request headers, like
Authorization
- tbd.
Simple Example
A collection looks like this:
// TasksCollection.js
const apiPath = '/api'
import adapter from 'mobx-rest-fetch-adapter'
import { apiClient, Collection, Model } from 'mobx-rest'
// We will use the adapter to make the `xhr` calls
apiClient(adapter, { apiPath })
class Task extends Model { }
class Tasks extends Collection {
url () { return `/tasks` }
model () { return Task }
}
// We instantiate the collection and export it as a singleton
export default new Tasks()
And here an example of how to use React with it:
import tasksCollection from './TasksCollection'
import { computed } from 'mobx'
import { observer } from 'mobx-react'
@observer
class Task extends React.Component {
onClick () {
this.props.task.save({ resolved: true })
}
render () {
return (
<li key={task.id}>
<button onClick={this.onClick.bind(this)}>
resolve
</button>
{this.props.task.get('name')}
</li>
)
}
}
@observer
class Tasks extends React.Component {
componentWillMount () {
// This will call `/api/tasks?all=true`
tasksCollection.fetch({ data: { all: true } })
}
@computed
get activeTasks () {
return tasksCollection.filter({ resolved: false })
}
render () {
if (tasksCollection.isRequest('fetching')) {
return <span>Fetching tasks...</span>
}
return (
<div>
<span>{this.activeTasks.length} tasks</span>
<ul>{activeTasks.map((task) => <Task task={task} />)}</ul>
</div>
)
}
}
State shape
Your collections and models will have the following state shape:
Collection
models: Array<Model> // This is where the models live
request: { // An ongoing request
label: string, // Examples: 'updating', 'creating', 'fetching', 'destroying' ...
abort: () => void, // A method to abort the ongoing request
progress: number // If uploading a file, represents the progress
},
error: { // A failed request
label: string, // Examples: 'updating', 'creating', 'fetching', 'destroying' ...
body: Object, // A string representing the error
}
Model
attributes: Object // The resource attributes
optimisticId: string, // Client side id. Used for optimistic updates
request: { // An ongoing request
label: string, // Examples: 'updating', 'creating', 'fetching', 'destroying' ...
abort: () => void, // A method to abort the ongoing request
},
error: { // A failed request
label: string, // Examples: 'updating', 'creating', 'fetching', 'destroying' ...
body: string, // A string representing the error
},
FAQ
How do I create relations between the models?
This is something that mobx makes really easy to achieve:
import usersCollection from './UsersCollections'
import { computed } from 'mobx'
class Task extends Model {
@computed
author () {
const userId = this.get('userId')
return usersCollection.get(userId) ||
usersCollection.nullObject()
}
}
I recommend to always fallback with a null object which will facilitate a ton to write code like task.author.get('name')
.
Where is it used?
Developed and battle tested in production in Factorial
License
(The MIT License)
Copyright (c) 2017 Pau Ramon masylum@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.