This commit is contained in:
syuilo
2018-04-20 13:31:43 +09:00
parent 8a8d97b8c7
commit 4953842ff1
9 changed files with 165 additions and 25 deletions

View File

@@ -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<IFavorite>('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<any>(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);
});