[www] added Article model

This commit is contained in:
Roman Timashev committed 2017-10-15 02:09:26 +03:00
1 parent b1d25143ec
commit 50b3f7fbd5
2 files changed
+109

No files matched your search

+107
View File
@@ -0,0 +1,107 @@
const Data = require('./Data')
const Image = require('./Image')
const Config = require('./Config')
const {find, findOne, total} = require('../lib/store')
const store = () => Data.getStore(Article)
class Article {
static async find(query, options = {}) {
const items = await find(store(), query, options)
return Promise.all(items.map(processArticle))
}
static async findById(id) {
const item = await findOne(store(), {id})
return !item
? null
: processArticle(item)
}
static async total(query = {}) {
return total(store(), query)
}
static async findPinned() {
const now = new Date()
const query = {until: {$gte: now}}
return Article.find(query, {
sort: {date: -1},
})
}
constructor(data) {
this.id = data.id
this.images = data.images
this.post = data.post
this.folder = data.folder
this.date = data.date
this.title = data.title
this.until = data.until
this.tags = data.tags
this.content = data.content
this.hash = data.hash
this.type = data.type
this.origin = data.origin
this.file = data.file
this.version = data.version
this.preview = data.preview
this.url = `/article/${this.id}`
}
plain() {
return {
id: this.id,
images: this.images,
post: this.post,
folder: this.folder,
date: this.date,
title: this.title,
until: this.until,
tags: this.tags,
content: this.content,
hash: this.hash,
type: this.type,
origin: this.origin,
file: this.file,
version: this.version,
preview: this.preview,
url: this.url,
}
}
}
const previewFromImage = (imgs = []) => imgs.length
? imgs[0]
: null
async function resolveDefaultPreview() {
const config = await Config.findConfig()
if (!config) return null
return Image.findByFile(config.articleCardDefaultPreview)
}
async function processArticle(article) {
let preview = null
const previewId = article.preview
? article.preview
: previewFromImage(article.images)
if (previewId) {
preview = await Image.findById(previewId)
} else {
preview = await resolveDefaultPreview()
}
return new Article({
...article,
preview,
})
}
module.exports = Article
+2
View File
@@ -1,4 +1,5 @@
const Data = require('./Data')
const Article = require('./Article')
const Album = require('./Album')
const Teacher = require('./Teacher')
const Document = require('./Document')
@@ -29,6 +30,7 @@ export function id(i) {
}
function init(db) {
Data.setStore(Article, db.collection('articles'))
Data.setStore(Album, db.collection('albums'))
Data.setStore(Image, db.collection('images'))
Data.setStore(Teacher, db.collection('collective'))