Simulate the service layer page

Simulate the service layer (can-fixture)

The problem

Simulate a service layer that handles the following requests and responses:

GET /api/todos

-> GET /api/todos

<- {
    "data": [
      { "name": "mow lawn", "complete": false, "id": 5 },
      { "name": "dishes", "complete": true, "id": 6 },
      { "name": "learn canjs", "complete": false, "id": 7 }
    ]
}

This should also support a sort and complete params like:

-> GET /api/todos?sort=name&complete=true

GET /api/todos/{id}

-> GET /api/todos/5

<- { "name": "mow lawn", "complete": false, "id": 5 }

POST /api/todos

-> POST /api/todos
   {"name": "learn can-fixture", "complete": false}

<- {"id": 8}

PUT /api/todos/{id}

-> PUT /api/todos/8
   {"name": "learn can-fixture", "complete": true}

<- {"id": 8, "name": "learn can-fixture", "complete": true}

DELETE /api/todos/{id}

-> DELETE /api/todos/8

<- {}

What you need to know

  • The can-fixture Presentation

  • fixture - is used to trap AJAX requests like:

    fixture("/api/entities", function(request) {
      request.data.folderId //-> "1"
    
      return {data: [...]}
    })
    
  • can-fixture.store - can be used to automatically filter records if given a schema.

    const entities = [ .... ];
    const entitiesStore = fixture.store( entities, entitiesAlgebra );
    fixture("/api/entities/{id}", entitiesStore);
    

The solution

Click to see the solution

Create models/todos-fixture.js as follows:

// models/todos-fixture.js
import {fixture} from "can";
import Todo from "./todo";

const todoStore = fixture.store([
    { name: "mow lawn", complete: false, id: "5" },
    { name: "dishes", complete: true, id: "6" },
    { name: "learn canjs", complete: false, id: "7" }
], Todo);

fixture("/api/todos/{id}", todoStore);
fixture.delay = 500;

export default todoStore;