Connection page
Connect the Todo model to the service layer (can-connect)
The problem
- Decorate
Todo
with methods so it can get, create, updated, and delete todos at the/api/todos
service. Specifically:Todo.getList()
which callsGET /api/todos
Todo.get({id: 5})
which callsGET /api/todos/5
todo.save()
which callsPOST /api/todos
iftodo
doesn’t have anid
orPUT /api/todos/{id}
if thetodo
has an id.todo.destroy()
which callsDELETE /api/todos/5
What you need to know
The can-connect Presentation up to and including Migrate 2 can-connect.
baseMap can decorate a
DefineMap
with methods that connect it to a restful URL like:baseMap({ Map: Type, url: "URL", algebra: algebra })
The solution
Click to see the solution
Update models/todo.js to the following:
// models/todo.js
import {DefineMap, DefineList, realtimeRestModel} from "can";
const Todo = DefineMap.extend("Todo", {
id: {type: "string", identity: true},
name: "string",
complete: {
type: "boolean",
default: false
},
toggleComplete() {
this.complete = !this.complete;
}
});
Todo.List = DefineList.extend("TodoList", {
"#": Todo,
get active() {
return this.filter({
complete: false
});
},
get complete() {
return this.filter({
complete: true
});
},
get allComplete() {
return this.length === this.complete.length;
}
});
Todo.connection = realtimeRestModel({
url: "/api/todos/{id}",
Map: Todo,
List: Todo.List
});
export default Todo;