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