monkeeShark/src/api/serializers/app.ts

84 lines
1.5 KiB
TypeScript
Raw Normal View History

2016-12-28 22:49:51 +00:00
/**
* Module dependencies
*/
import * as mongo from 'mongodb';
2017-01-02 21:03:19 +00:00
import deepcopy = require('deepcopy');
2016-12-28 22:49:51 +00:00
import App from '../models/app';
import AccessToken from '../models/access-token';
2017-01-17 00:17:52 +00:00
import config from '../../conf';
2016-12-28 22:49:51 +00:00
/**
* Serialize an app
*
2017-03-01 08:37:01 +00:00
* @param {any} app
* @param {any} me?
* @param {any} options?
* @return {Promise<any>}
2016-12-28 22:49:51 +00:00
*/
export default (
app: any,
me?: any,
options?: {
2017-03-03 10:48:00 +00:00
includeSecret?: boolean,
includeProfileImageIds?: boolean
2016-12-28 22:49:51 +00:00
}
) => new Promise<any>(async (resolve, reject) => {
const opts = options || {
includeSecret: false,
includeProfileImageIds: false
};
let _app: any;
// Populate the app if 'app' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(app)) {
_app = await App.findOne({
_id: app
});
} else if (typeof app === 'string') {
2017-02-22 03:59:47 +00:00
_app = await App.findOne({
2016-12-28 22:49:51 +00:00
_id: new mongo.ObjectID(app)
});
} else {
_app = deepcopy(app);
}
// Me
if (me && !mongo.ObjectID.prototype.isPrototypeOf(me)) {
if (typeof me === 'string') {
me = new mongo.ObjectID(me);
} else {
me = me._id;
}
}
// Rename _id to id
_app.id = _app._id;
delete _app._id;
delete _app.name_id_lower;
// Visible by only owner
if (!opts.includeSecret) {
delete _app.secret;
}
_app.icon_url = _app.icon != null
? `${config.drive_url}/${_app.icon}`
: `${config.drive_url}/app-default.jpg`;
if (me) {
// 既に連携しているか
const exist = await AccessToken.count({
2016-12-28 22:49:51 +00:00
app_id: _app.id,
user_id: me,
}, {
2017-03-01 08:37:01 +00:00
limit: 1
});
2016-12-28 22:49:51 +00:00
_app.is_authorized = exist === 1;
}
resolve(_app);
});