2017-11-21 03:40:09 +09:00
|
|
|
import $ from 'cafy';
|
2018-03-29 20:32:18 +09:00
|
|
|
import Subscription from '../../../../models/sw-subscription';
|
2018-09-01 08:13:18 +09:00
|
|
|
import config from '../../../../config';
|
2018-11-02 13:47:44 +09:00
|
|
|
import define from '../../define';
|
2017-11-21 03:40:09 +09:00
|
|
|
|
2018-07-17 04:36:44 +09:00
|
|
|
export const meta = {
|
2018-11-02 12:49:08 +09:00
|
|
|
requireCredential: true,
|
2018-07-17 04:36:44 +09:00
|
|
|
|
2018-11-02 12:49:08 +09:00
|
|
|
params: {
|
|
|
|
|
endpoint: {
|
|
|
|
|
validator: $.str
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
auth: {
|
|
|
|
|
validator: $.str
|
|
|
|
|
},
|
2017-11-21 03:40:09 +09:00
|
|
|
|
2018-11-02 12:49:08 +09:00
|
|
|
publickey: {
|
|
|
|
|
validator: $.str
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
2017-11-21 03:40:09 +09:00
|
|
|
|
2018-11-02 13:47:44 +09:00
|
|
|
export default define(meta, (ps, user) => new Promise(async (res, rej) => {
|
2017-11-21 03:40:09 +09:00
|
|
|
// if already subscribed
|
|
|
|
|
const exist = await Subscription.findOne({
|
2018-03-29 14:48:47 +09:00
|
|
|
userId: user._id,
|
2018-11-02 12:49:08 +09:00
|
|
|
endpoint: ps.endpoint,
|
|
|
|
|
auth: ps.auth,
|
|
|
|
|
publickey: ps.publickey,
|
2018-03-29 14:48:47 +09:00
|
|
|
deletedAt: { $exists: false }
|
2017-11-21 03:40:09 +09:00
|
|
|
});
|
|
|
|
|
|
2018-09-01 08:13:18 +09:00
|
|
|
if (exist != null) {
|
|
|
|
|
return res({
|
|
|
|
|
state: 'already-subscribed',
|
2018-12-19 06:47:47 +09:00
|
|
|
key: config.sw.publicKey
|
2018-09-01 08:13:18 +09:00
|
|
|
});
|
2017-11-21 03:40:09 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await Subscription.insert({
|
2018-03-29 14:48:47 +09:00
|
|
|
userId: user._id,
|
2018-11-02 12:49:08 +09:00
|
|
|
endpoint: ps.endpoint,
|
|
|
|
|
auth: ps.auth,
|
|
|
|
|
publickey: ps.publickey
|
2017-11-21 03:40:09 +09:00
|
|
|
});
|
|
|
|
|
|
2018-09-01 08:13:18 +09:00
|
|
|
res({
|
|
|
|
|
state: 'subscribed',
|
2018-12-19 06:47:47 +09:00
|
|
|
key: config.sw.publicKey
|
2018-09-01 08:13:18 +09:00
|
|
|
});
|
2018-11-02 13:47:44 +09:00
|
|
|
}));
|