Last active
June 15, 2018 16:08
-
-
Save graphicbeacon/016bdf38a0dd7579660ab02815bac1f0 to your computer and use it in GitHub Desktop.
Sample code for "Building RESTful Web APIs with Dart, Aqueduct and PostgreSQL (Bonus content)" post on Medium (7)
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 { | |
//.. | |
@httpPost | |
Future<Response> addBook(@HTTPBody() Book book) async { | |
var query = new Query<Book>()..values = book; | |
var insertedBook = await query.insert(); | |
// Insert authors from payload | |
await Future.forEach(book.authors, (Author a) async { | |
var author = new Query<Author>() | |
..values = a | |
..values.book = insertedBook; // set foreign key to inserted book | |
return (await author.insert()); | |
}); | |
var insertedBookQuery = new Query<Book>() | |
..where.id = whereEqualTo(insertedBook.id); | |
insertedBookQuery.join(set: (book) => book.authors) | |
..returningProperties((Author author) => [author.name]); // <-- Specify the columns returned for each author in the response | |
return new Response.ok(await insertedBookQuery.fetchOne()); | |
} | |
//.. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment