Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon
Last active May 22, 2018 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphicbeacon/610dbc2948a743ca33c81d9409335a58 to your computer and use it in GitHub Desktop.
Save graphicbeacon/610dbc2948a743ca33c81d9409335a58 to your computer and use it in GitHub Desktop.
Sample code for "Building RESTful Web APIs with Dart, Aqueduct and PostgreSQL (Part 3)" post on Medium (5)
class BooksController extends HTTPController {
@httpGet
Future<Response> getAllBooks() async {
var query = new Query<Book>();
return new Response.ok(await query.fetch());
}
@httpGet
Future<Response> getBook(@HTTPPath("index") int idx) async {
var query = new Query<Book>()..where.id = whereEqualTo(idx);
var book = await query.fetchOne();
if (book == null) {
return new Response.notFound(body: 'Book does not exist')
..contentType = ContentType.TEXT;
}
return new Response.ok(book);
}
@httpPost
Future<Response> addBook(@HTTPBody() Book book) async {
var query = new Query<Book>()..values = book;
return new Response.ok(await query.insert());
}
@httpPut
Future<Response> updateBook(@HTTPPath("index") int idx, @HTTPBody() Book book) async {
var query = new Query<Book>()
..values = book
..where.id = whereEqualTo(idx);
var updatedBook = await query.updateOne();
if (updatedBook == null) {
return new Response.notFound(body: 'Book does not exist');
}
return new Response.ok(updatedBook);
}
@httpDelete
Future<Response> deleteBook(@HTTPPath("index") int idx) async {
var query = new Query<Book>()..where.id = whereEqualTo(idx);
var deletedBookId = await query.delete();
if (deletedBookId == 0) {
return new Response.notFound(body: 'Book does not exist');
}
return new Response.ok('Successfully deleted book.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment