hippofish/src/server/api/endpoints/sw/register.ts
YuzuRyo61 a07d753da8
APIドキュメントの改善 (#6757)
* Update api document in admin/announcements

* Update api document in announcements

* Update api document in i/read-announcements

* Update api document in username/available

* Update api document & Fix typo in API 403 error

* Update api document

* Update api document

* Update api document

* Fix API permission definition

* Update api document

* Update api document

* Update api document

* Update api document

* Update api document

* Update api document

* Update api document

* Update api document

* Fix bug in users (api)

* Apply reviews #6757

* Apply reviews #6757

Co-authored-by: syuilo <Syuilotan@yahoo.co.jp>
2021-03-06 22:34:11 +09:00

74 lines
1.4 KiB
TypeScript

import $ from 'cafy';
import define from '../../define';
import { fetchMeta } from '../../../../misc/fetch-meta';
import { genId } from '../../../../misc/gen-id';
import { SwSubscriptions } from '../../../../models';
export const meta = {
tags: ['account'],
requireCredential: true as const,
params: {
endpoint: {
validator: $.str
},
auth: {
validator: $.str
},
publickey: {
validator: $.str
}
},
res: {
type: 'object' as const,
optional: false as const, nullable: false as const,
properties: {
state: {
type: 'string' as const,
optional: false as const, nullable: false as const,
enum: ['already-subscribed', 'subscribed']
},
key: {
type: 'string' as const,
optional: false as const, nullable: false as const
}
}
}
};
export default define(meta, async (ps, user) => {
// if already subscribed
const exist = await SwSubscriptions.findOne({
userId: user.id,
endpoint: ps.endpoint,
auth: ps.auth,
publickey: ps.publickey,
});
const instance = await fetchMeta(true);
if (exist != null) {
return {
state: 'already-subscribed',
key: instance.swPublicKey
};
}
await SwSubscriptions.save({
id: genId(),
createdAt: new Date(),
userId: user.id,
endpoint: ps.endpoint,
auth: ps.auth,
publickey: ps.publickey
});
return {
state: 'subscribed',
key: instance.swPublicKey
};
});