From 4953842ff1c65fc850c856e11598e9901ff7c6e1 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 20 Apr 2018 13:31:43 +0900 Subject: :v: --- src/models/favorite.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'src/models') diff --git a/src/models/favorite.ts b/src/models/favorite.ts index 5387b29457..d24833f191 100644 --- a/src/models/favorite.ts +++ b/src/models/favorite.ts @@ -1,5 +1,7 @@ import * as mongo from 'mongodb'; +import deepcopy = require('deepcopy'); import db from '../db/mongodb'; +import { pack as packNote } from './note'; const Favorite = db.get('favorites'); Favorite.createIndex(['userId', 'noteId'], { unique: true }); @@ -38,3 +40,35 @@ export async function deleteFavorite(favorite: string | mongo.ObjectID | IFavori _id: f._id }); } + +/** + * Pack a favorite for API response + */ +export const pack = ( + favorite: any, + me: any +) => new Promise(async (resolve, reject) => { + let _favorite: any; + + // Populate the favorite if 'favorite' is ID + if (mongo.ObjectID.prototype.isPrototypeOf(favorite)) { + _favorite = await Favorite.findOne({ + _id: favorite + }); + } else if (typeof favorite === 'string') { + _favorite = await Favorite.findOne({ + _id: new mongo.ObjectID(favorite) + }); + } else { + _favorite = deepcopy(favorite); + } + + // Rename _id to id + _favorite.id = _favorite._id; + delete _favorite._id; + + // Populate note + _favorite.note = await packNote(_favorite.noteId, me); + + resolve(_favorite); +}); -- cgit v1.2.3-freya