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

101 lines
2.1 KiB
TypeScript
Raw Normal View History

2018-03-06 08:54:56 -08:00
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import db from '../../db/mongodb';
2018-03-07 00:48:32 -08:00
import { IUser, pack as packUser } from './user';
2018-03-06 08:54:56 -08:00
const Game = db.get<IGame>('othello_games');
export default Game;
export interface IGame {
_id: mongo.ObjectID;
created_at: Date;
2018-03-08 00:57:57 -08:00
started_at: Date;
user1_id: mongo.ObjectID;
user2_id: mongo.ObjectID;
user1_accepted: boolean;
user2_accepted: boolean;
/**
* ()
* 1 ... user1
* 2 ... user2
*/
black: number;
is_started: boolean;
2018-03-07 01:45:16 -08:00
is_ended: boolean;
winner_id: mongo.ObjectID;
2018-03-06 08:54:56 -08:00
logs: any[];
2018-03-08 00:57:57 -08:00
settings: {
2018-03-09 01:11:10 -08:00
map: string[];
2018-03-08 00:57:57 -08:00
bw: string | number;
is_llotheo: boolean;
2018-03-10 01:22:54 -08:00
can_put_everywhere: boolean;
2018-03-10 04:23:00 -08:00
looped_board: boolean;
2018-03-08 00:57:57 -08:00
};
2018-03-06 08:54:56 -08:00
}
/**
* Pack an othello game for API response
*/
export const pack = (
2018-03-07 00:48:32 -08:00
game: any,
2018-03-09 01:11:10 -08:00
me?: string | mongo.ObjectID | IUser,
options?: {
detail?: boolean
}
2018-03-06 08:54:56 -08:00
) => new Promise<any>(async (resolve, reject) => {
2018-03-09 01:11:10 -08:00
const opts = Object.assign({
detail: true
}, options);
2018-03-08 00:57:57 -08:00
let _game: any;
// Populate the game if 'game' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(game)) {
_game = await Game.findOne({
_id: game
});
} else if (typeof game === 'string') {
_game = await Game.findOne({
_id: new mongo.ObjectID(game)
});
} else {
_game = deepcopy(game);
}
2018-03-06 08:54:56 -08:00
2018-03-07 00:48:32 -08: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-06 08:54:56 -08:00
// Rename _id to id
_game.id = _game._id;
delete _game._id;
2018-03-09 01:11:10 -08:00
if (opts.detail === false) {
delete _game.logs;
delete _game.settings.map;
2018-03-09 01:29:27 -08:00
} else {
// 互換性のため
if (_game.settings.map.hasOwnProperty('size')) {
_game.settings.map = _game.settings.map.data.match(new RegExp(`.{1,${_game.settings.map.size}}`, 'g'));
}
2018-03-09 01:11:10 -08:00
}
2018-03-07 00:48:32 -08:00
// Populate user
2018-03-08 00:57:57 -08:00
_game.user1 = await packUser(_game.user1_id, meId);
_game.user2 = await packUser(_game.user2_id, meId);
2018-03-07 01:55:02 -08:00
if (_game.winner_id) {
_game.winner = await packUser(_game.winner_id, meId);
} else {
_game.winner = null;
}
2018-03-07 00:48:32 -08:00
2018-03-06 08:54:56 -08:00
resolve(_game);
});