misskey/src/api/models/othello-game.ts

50 lines
1.1 KiB
TypeScript
Raw Normal View History

2018-03-07 01:54:56 +09:00
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import db from '../../db/mongodb';
2018-03-07 17:48:32 +09:00
import { IUser, pack as packUser } from './user';
2018-03-07 01:54:56 +09:00
const Game = db.get<IGame>('othello_games');
export default Game;
export interface IGame {
_id: mongo.ObjectID;
created_at: Date;
black_user_id: mongo.ObjectID;
white_user_id: mongo.ObjectID;
2018-03-07 18:45:16 +09:00
turn_user_id: mongo.ObjectID;
is_ended: boolean;
winner_id: mongo.ObjectID;
2018-03-07 01:54:56 +09:00
logs: any[];
}
/**
* Pack an othello game for API response
*/
export const pack = (
2018-03-07 17:48:32 +09:00
game: any,
me?: string | mongo.ObjectID | IUser
2018-03-07 01:54:56 +09:00
) => new Promise<any>(async (resolve, reject) => {
2018-03-07 17:48:32 +09:00
// Me
const meId: mongo.ObjectID = me
? mongo.ObjectID.prototype.isPrototypeOf(me)
? me as mongo.ObjectID
: typeof me === 'string'
? new mongo.ObjectID(me)
: (me as IUser)._id
: null;
2018-03-07 01:54:56 +09:00
const _game = deepcopy(game);
// Rename _id to id
_game.id = _game._id;
delete _game._id;
2018-03-07 17:48:32 +09:00
// Populate user
_game.black_user = await packUser(_game.black_user_id, meId);
_game.white_user = await packUser(_game.white_user_id, meId);
2018-03-07 18:45:16 +09:00
_game.winner = await packUser(_game.winner_id, meId);
2018-03-07 17:48:32 +09:00
2018-03-07 01:54:56 +09:00
resolve(_game);
});