Move everything to models and services #17

Merged
konrad merged 82 commits from refactor/models into master 2019-03-02 10:25:10 +00:00
Showing only changes of commit f7d79c785c - Show all commits

View File

@ -16,6 +16,8 @@ A service takes (in most cases) a model and returns one.
* [Before Request](#before-request)
* [After Request?](#after-request-)
* [Models](#models)
* [Default Values](#default-values)
* [Constructor](#constructor)
## Services
@ -104,3 +106,65 @@ Processing raw api data should be done in the constructor of the model, see more
## Models
Models are a bit simpler than services.
They usually consist of a declaration of defaults and an optional constructor.
Models are located in `src/models`.
Each model should extend the `AbstractModel`.
This handles the default value parsing.
A model _does not_ handle any http requests, that's what services are for.
A simple model can look like this:
```javascript
import AbstractModel from './abstractModel'
import TaskModel from './task'
import UserModel from './user'
export default class ListModel extends AbstractModel {
constructor(data) {
// The constructor of AbstractModel handles all the default parsing.
super(data)
// Make all tasks to task models
this.tasks = this.tasks.map(t => {
return new TaskModel(t)
})
this.owner = new UserModel(this.owner)
}
// Default attributes that define the "empty" state.
defaults() {
return {
id: 0,
title: '',
description: '',
owner: UserModel,
tasks: [],
namespaceID: 0,
created: 0,
updated: 0,
}
}
}
```
#### Default values
The `defaults()` functions provides all default values.
The `AbstractModel` constructor will take all the data provided to it, and fill any non-existent,
`undefined` or `null` value with the default provided by the function.
#### Constructor
The `AbstractModel` constructor handles all the default value parsing.
In your model, the constructor can do additional parsing, like making js date object from unix timestamps
or parsing the contents of a child-array into a model.
If the model does nothing like this, you don't need to define a constructor at all.
The parent will handle it all.