From 0e4a111f81cceed275d9bec2695f6e401fb654d8 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 12 Nov 2021 02:02:25 +0900 Subject: refactoring Resolve #7779 --- .../src/server/api/endpoints/sw/register.ts | 74 ++++++++++++++++++++++ .../src/server/api/endpoints/sw/unregister.ts | 22 +++++++ 2 files changed, 96 insertions(+) create mode 100644 packages/backend/src/server/api/endpoints/sw/register.ts create mode 100644 packages/backend/src/server/api/endpoints/sw/unregister.ts (limited to 'packages/backend/src/server/api/endpoints/sw') diff --git a/packages/backend/src/server/api/endpoints/sw/register.ts b/packages/backend/src/server/api/endpoints/sw/register.ts new file mode 100644 index 0000000000..6e14ba2669 --- /dev/null +++ b/packages/backend/src/server/api/endpoints/sw/register.ts @@ -0,0 +1,74 @@ +import $ from 'cafy'; +import define from '../../define'; +import { fetchMeta } from '@/misc/fetch-meta'; +import { genId } from '@/misc/gen-id'; +import { SwSubscriptions } from '@/models/index'; + +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.insert({ + id: genId(), + createdAt: new Date(), + userId: user.id, + endpoint: ps.endpoint, + auth: ps.auth, + publickey: ps.publickey + }); + + return { + state: 'subscribed', + key: instance.swPublicKey + }; +}); diff --git a/packages/backend/src/server/api/endpoints/sw/unregister.ts b/packages/backend/src/server/api/endpoints/sw/unregister.ts new file mode 100644 index 0000000000..817ad1f517 --- /dev/null +++ b/packages/backend/src/server/api/endpoints/sw/unregister.ts @@ -0,0 +1,22 @@ +import $ from 'cafy'; +import define from '../../define'; +import { SwSubscriptions } from '../../../../models'; + +export const meta = { + tags: ['account'], + + requireCredential: true as const, + + params: { + endpoint: { + validator: $.str + }, + } +}; + +export default define(meta, async (ps, user) => { + await SwSubscriptions.delete({ + userId: user.id, + endpoint: ps.endpoint, + }); +}); -- cgit v1.2.3-freya