Skip to content

Instantly share code, notes, and snippets.

@ForceTower
Created May 8, 2020 23:11
Show Gist options
  • Save ForceTower/1d9acd12e772fe352bedcd5e640de7e2 to your computer and use it in GitHub Desktop.
Save ForceTower/1d9acd12e772fe352bedcd5e640de7e2 to your computer and use it in GitHub Desktop.

Revisions

  1. ForceTower created this gist May 8, 2020.
    35 changes: 35 additions & 0 deletions article_dao.dart
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    @Query('SELECT * FROM article ORDER BY publishedAt DESC')
    Stream<List<Article>> getAllArticles();

    @Query('SELECT Author.*, _junction.articleId as articleId FROM ArticleAuthor AS _junction inner join Author ON (_junction.authorId = Author.id) WHERE _junction.articleId IN (:ids)')
    Future<List<AuthorArticleId>> getAuthorsFromArticles(List<int> ids);

    Stream<List<ArticleWithAuthor>> getAllArticlesWithAuthors() {
    final stream = getAllArticles();
    final controller = StreamController<List<ArticleWithAuthor>>.broadcast();

    Future<void> getInternalAuthors(List<Article> articles) async {
    final ids = articles.map((it) => it.id).toList();
    final authors = await getAuthorsFromArticles(ids);
    final result = articles.map((element) {
    final data = authors.firstWhere((it) => it.articleId == element.id);
    Author author;
    if (data != null) {
    author = Author(data.id, data.name, data.slug, data.avatar);
    }
    return ArticleWithAuthor(
    element,
    author
    );
    }).toList();
    controller.add(result);
    }

    stream.listen(
    (articles) async {
    getInternalAuthors(articles);
    },
    onDone: () => controller.close()
    );
    return controller.stream;
    }
    10 changes: 10 additions & 0 deletions author_article_id.dart
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    @DatabaseView('SELECT Author.*, _junction.articleId as articleId FROM ArticleAuthor AS _junction inner join Author ON (_junction.authorId = Author.id)')
    class AuthorArticleId {
    final int id;
    final String name;
    final String slug;
    final String avatar;
    final int articleId;

    AuthorArticleId(this.id, this.name, this.slug, this.avatar, this.articleId);
    }