Created
May 16, 2018 22:13
-
-
Save graphicbeacon/458fbe7192012a058a942a1d65c20ad3 to your computer and use it in GitHub Desktop.
Sample code for "Building RESTful Web APIs with Dart, Aqueduct and PostgreSQL (Part 2)" post on Medium (5)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BooksController extends HTTPController { | |
@httpGet | |
Future<Response> getAll() async => new Response.ok(books); | |
@httpGet | |
Future<Response> getSingle(@HTTPPath("index") int idx) async { | |
if (idx < 0 || idx > books.length - 1) { // index out of range | |
return new Response.notFound(body: 'Book does not exist'); | |
} | |
return new Response.ok(books[idx]); | |
} | |
@httpPost | |
Future<Response> addSingle() async { | |
var book = request.body.asMap(); // `request` represents the current request. This is a property inside HTTPController base class | |
books.add(book); | |
return new Response.ok(book); | |
} | |
@httpPut | |
Future<Response> replaceSingle(@HTTPPath("index") int idx) async { | |
if (idx < 0 || idx > books.length - 1) { // index out of range | |
return new Response.notFound(body: 'Book does not exist'); | |
} | |
var body = request.body.asMap(); | |
for (var i = 0; i < books.length; i++) { | |
if (i == idx) { | |
books[i]["title"] = body["title"]; | |
books[i]["author"] = body["author"]; | |
books[i]["year"] = body["year"]; | |
} | |
} | |
return new Response.ok(body); | |
} | |
@httpDelete | |
Future<Response> delete(@HTTPPath("index") int idx) async { | |
if (idx < 0 || idx > books.length - 1) { // index out of range | |
return new Response.notFound(body: 'Book does not exist'); | |
} | |
books.removeAt(idx); | |
return new Response.ok('Book successfully deleted.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment