Sinon Fake RESTful API

by Ryan Morris

HTML

<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/1.15.4/sinon.min.js"></script>
<h1>
Books
</h1>

<ul id="book-list">

</ul>

<form id="new-book">
<input type="text" name="title" placeholder="Enter a title">
<input type="submit">
</form>

JavaScript

var server = sinon.fakeServer.create(),
	books = [{
  	id: 1,
    title: "Grapes of Wraith"
  },{
  	id: 2,
    title: "Game of Thrones"
  }, {
  	id: 3,
    title: "Of Mice and Men"
  }, {
  	id: 4,
    title: "Red Mars"
  }, {
  	id: 5,
    title: "Rendezvous with Rama"
  }
];

// tell the server to behave synchronously
server.respondImmediately = true;

// set up our endpoints

// GET /books will return a list of books
server.respondWith("GET", "/books", [
	200, 
  { "Content-Type": "application/json" },
  JSON.stringify(books)
]);

// POST /books will return a successfully created book
server.respondWith("POST", "/books",  
  function(request) {
  	
    console.log("Post request:", request);
    
    var newBook = JSON.parse(request.requestBody)
    
    console.log("New book:", newBook);

  	// we could perform some semi-fake validation here
  	// and return an error response if the data is
  	// not to our liking for this simulation
    if (newBook.title) {
    	request.respond(
        200, 
        { "Content-Type": "application/json" },
        JSON.stringify(newBook)
      );
    } else {
      request.respond(
          200, 
          { "Content-Type": "application/json" },
          JSON.stringify({error: "Invalid data"})
        );
    }
    
  }
);

// Now we perform our requests
// We could set them up as requests that are triggered
// by user interaction, or other events in the page
// but for this example we're just making them immediately

var $bookList = $("#book-list");

var getRequest = $.ajax({
	url: "/books",
  method: "GET"
});

getRequest.done(function(response) {

	console.log("Get Request:", response);
  
  var newLis = '';
  
  for (var i=0; i<response.length; i++) {
  	newLis += "<li>" + response[i].title + "</li>";
  }
  
  $bookList.append(newLis);
  
});

$("#new-book").on('submit', function(e) {

	e.preventDefault();
  
  // We are setting up the data to submit as an object
  // we will later stringify
  // we are not using...