const ObjectID = require("mongodb").ObjectID; const {connect} = require('mm') module.exports = async (dbName='snippet') => { const {Savable, slice} = await connect(dbName) async function getModels({id}){ const SlicedSavable = slice([id, 'user']) class User extends SlicedSavable { constructor(...params){ super(...params) //TODO: calc likes count by getter (no two-way relation for this to avoid overflow on many Kilos of likes //cached like count, which incremented and decremented // //following and followers array } async getACL(){ return [this._id.toString(), "user"] } static get relations(){ //don't needed due to ___owner in most cases return { avatar : "userAvatar", } } } SlicedSavable.addClass(User) class OwnerSlicedSavable extends SlicedSavable { get owner(){ if (!this.___owner) return this.___owner return SlicedSavable.m.User.findOne({_id: ObjectID(this.___owner)}) } } class Image extends OwnerSlicedSavable { constructor(...params){ super(...params) } static async fromFileData(fileData){ try { let image = new Image({}) image.fileData = fileData image.url = `images/${fileData.filename}` image.originalFileName = fileData.originalname await image.save() return image; } catch(e){ console.log('wrong file') } } static get relations(){ return { userAvatar: "avatar", //if it is ava } } } SlicedSavable.addClass(Image) class Snippet extends OwnerSlicedSavable { constructor(...params){ super(...params) } static get relations(){ return { comments: "snippet", files: "snippet", } } static get guestRelations(){ return ["comments"] } } SlicedSavable.addClass(Snippet) class Comment extends OwnerSlicedSavable { constructor(...params){ super(...params) //TODO: calc likes count by getter (no two-way relation for this to avoid overflow on many Kilos of likes //cached like count, which incremented and decremented } static get relations(){ return { snippet: ["comments"], answers: "answerTo", answerTo: ["answers"], } } static get guestRelations(){ return ["answers"] } } SlicedSavable.addClass(Comment) class File extends OwnerSlicedSavable { constructor(...params){ super(...params) } static get relations(){ return { snippet: ["files"], } } } SlicedSavable.addClass(File) const thisUser = await Savable.m.User.findOne({_id: ObjectID(id)}) return {models: { SlicedSavable, ...SlicedSavable.classes }, thisUser} } return { Savable, slice, getModels } }