SUW15 – v.36 torsdag – exempelkod ”Böcker och bokhyllor”

En enkel app.js, som läser in en books.json-fil och kan routa med express till en eller alla böcker:

(se längre ner för en version med en klass)


// dependencies var express = require('express'); var fs = require('fs'); // other variables var booksJSON = './data/books.json'; var app = express(); // A method to get our books // Note that it is asyncronous and needs to respond over a callback function getBooks(isbn, callback){ fs.readFile(booksJSON, function(err, JsonStr){ var books = JSON.parse(JsonStr); if(isbn){ books.forEach(function(book){ if(book.isbn == isbn){ callback(book); return; } }) }else{ callback(books); } }); } // express routes: app.get('/', function(request, response){ response.send('<a href="books">Books</a>'); }); app.get('/books/:isbn?', function (request, response) { // here we call an asyncronous function getBooks(request.params.isbn, function(result){ // we respond inside the callback of the async function response.send(JSON.stringify(result)); }); }); // server listens at port :3000 app.listen(3000);

Exempel på books.json


[ { "isbn": "9789137149059", "title":"Slutet på sommaren", "author": "Anders De la Motte" }, { "isbn": "9789187343766", "title":"Jag är här", "author": "Clélie Avit" }, { "isbn": "9789164204943", "title": "Äkta amerikanska jeans", "author": "Jan Guillou" } ]

En lite mer utvecklad app.js som använder en Book.class för att ge dess böcker klassinstanser:


// dependencies var express = require('express'); var fs = require('fs'); // classes var Book = require('./classes/Book.class.js'); // other variables var booksJSON = './data/books.json'; var app = express(); // A method to get our books // Note that it is asyncronous and needs to respond over a callback function getBooks(isbn, callback){ fs.readFile(booksJSON, function(err, JsonStr){ var books = JSON.parse(JsonStr), done = false; // classify books books.forEach(function(book, i){ books[i] = new Book(book); // a new object from a Class (with these props) }); // check for a unique identifier if(isbn){ books.forEach(function(book, i){ if(book.isbn == isbn){ // send a book (if we have not already responded) !done && callback(book); done = true; } }); // send error (if we have not already responded) !done && callback({error:'Book with ISBN ' + isbn + ' not found'}); // or send all books }else{ callback(books); } }); } // express routes: app.get('/', function(request, response){ response.send('<a href="books">Books</a>'); }); app.get('/books/:isbn?', function (request, response) { // here we call an asyncronous function getBooks(request.params.isbn, function(result){ // we respond inside the callback of the async function response.send(JSON.stringify(result)); }); }); // server listens at port :3000 app.listen(3000);

Och här har vi Book.class.js


'use strict'; module.exports = class Book{ constructor(props){ this.title = props.title; this.isbn = props.isbn; this.author = props.author; } }
0 votes