Skip to content

Commit

Permalink
feat: sort aritcle when add/save
Browse files Browse the repository at this point in the history
  • Loading branch information
ylc395 committed Nov 1, 2021
1 parent 08477ef commit fafcf76
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
21 changes: 19 additions & 2 deletions src/domain/service/ArticleService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ref, computed, InjectionKey, reactive, toRaw } from 'vue';
import { filter, pull, negate, uniq, findIndex, sortBy, compact, mapValues, pick } from 'lodash';
import { filter, pull, negate, uniq, findIndex, compact, mapValues, pick } from 'lodash';
import { singleton } from 'tsyringe';
import moment from 'moment';
import isValidFilename from 'valid-filename';
Expand Down Expand Up @@ -28,13 +28,14 @@ export class ArticleService {
}

private async init() {
const articles = sortBy(await this.pluginDataRepository.getArticles(), ['createdAt']).reverse();
const articles = (await this.pluginDataRepository.getArticles()) || undefined;

if (articles) {
await this.associateNotes(articles);
}

this.articles.push(...(articles ?? []));
this.sortByCreatedAt();
}

private async associateNotes(articles: Article[]) {
Expand All @@ -51,6 +52,15 @@ export class ArticleService {
}
}

private sortByCreatedAt() {
this.articles.sort((a1, a2) => {
const createdAt1 = moment.isMoment(a1.createdAt) ? a1.createdAt.valueOf() : a1.createdAt;
const createdAt2 = moment.isMoment(a2.createdAt) ? a2.createdAt.valueOf() : a2.createdAt;

return createdAt2 - createdAt1;
});
}

saveArticles() {
return this.pluginDataRepository.saveArticles(
toRaw(this.articles).map((article) => pick(article, REQUIRED_KEYS)),
Expand Down Expand Up @@ -96,6 +106,11 @@ export class ArticleService {
}
}

addArticles(article: Article) {
this.articles.push(article);
this.sortByCreatedAt();
}

selectAll(status: 'published' | 'unpublished') {
const articles =
status === 'published' ? this.publishedArticles.value : this.unpublishedArticles.value;
Expand All @@ -120,6 +135,8 @@ export class ArticleService {
}) as Partial<Article>;

Object.assign(this.articles[index], result);
this.sortByCreatedAt();

return this.saveArticles();
}

Expand Down
2 changes: 1 addition & 1 deletion src/domain/service/NoteService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export class NoteService {
article.url = this.articleService.getValidUrl(article.url);
}

this.articleService.articles.push(article);
this.articleService.addArticles(article);
}

this.notesToBeAdded.value = [];
Expand Down

0 comments on commit fafcf76

Please sign in to comment.