Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FCM topics subscription management #9

Merged
merged 6 commits into from
May 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,11 @@
"build": "rm -rf dist && node esbuild.mjs && cp -rf src/assets dist/assets && pnpm tsc && pnpm api-extractor run --local",
"generate:proto-definitions": "node scripts/generate-proto-definitions.mjs && pnpm prettier --write src/definitions/proto",
"generate:proto-ts": "node scripts/generate-proto-ts.mjs && pnpm prettier --write src/assets",
"prepublish": "pnpm test && pnpm build && pnpm version patch && cp LICENSE package.json README.md dist",
"prepublish": "pnpm test && pnpm build && cp LICENSE package.json README.md dist",
"test": "vitest run"
},
"sideEffects": false,
"type": "module",
"types": "index.d.ts",
"version": "1.0.26"
"version": "1.0.27-rc.0"
}
3 changes: 3 additions & 0 deletions src/apis/fcm-topics-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { RestAPI } from '@aracna/core'

export const FcmTopicsAPI = new RestAPI('https://iid.googleapis.com/')
26 changes: 26 additions & 0 deletions src/definitions/apis/fcm-topics-api-definitions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { FetchError, FetchResponse } from '@aracna/core'

export namespace FcmTopicsApiDefinitions {
export interface BatchAddRequestBody {
registration_tokens: string[]
to: string
}

export interface BatchAddResponseData {
results: object[]
}

export interface BatchAddResponse extends FetchResponse<BatchAddResponseData> {}

export interface BatchRemoveRequestBody extends BatchAddRequestBody {}

export interface BatchRemoveResponseData extends BatchAddResponseData {}

export interface BatchRemoveResponse extends FetchResponse<BatchRemoveResponseData> {}

export interface ErrorData {
error: string
}

export interface Error extends FetchError<ErrorData> {}
}
6 changes: 6 additions & 0 deletions src/definitions/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Storage } from '@aracna/core'
import { FcmApiDefinitions } from './apis/fcm-api-definitions.js'
import { FcmTopicsApiDefinitions } from './apis/fcm-topics-api-definitions.js'
import { McsState, McsTag } from './enums.js'
import { CheckinDefinitions } from './proto/checkin-definitions.js'
import { McsDefinitions } from './proto/mcs-definitions.js'
Expand Down Expand Up @@ -92,12 +93,17 @@ export interface FcmRegistration {

export interface FcmSubscription extends FcmRegistration {}

export interface FcmTopicSubscription extends FcmTopicsApiDefinitions.BatchAddResponseData {}
export interface FcmTopicUnsubscription extends FcmTopicsApiDefinitions.BatchRemoveResponseData {}

export interface GoogleServiceAccount {
client_email: string
private_key: string
project_id: string
}

export interface GoogleServiceAccountWithoutProjectID extends Omit<GoogleServiceAccount, 'project_id'> {}

export interface PostAcgRegisterOptions {
retry?: {
delay?: number
Expand Down
12 changes: 12 additions & 0 deletions src/functions/subscribe-to-fcm-topic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { FcmTopicSubscription, GoogleServiceAccountWithoutProjectID } from '../definitions/interfaces.js'
import { postFcmTopicsBatchAdd } from '../requests/fcm-topics-requests.js'

export async function subscribeToFcmTopic(
account: GoogleServiceAccountWithoutProjectID,
topic: string,
...tokens: string[]
): Promise<FcmTopicSubscription | Error>
export async function subscribeToFcmTopic(account: GoogleServiceAccountWithoutProjectID, topic: string, tokens: string[]): Promise<FcmTopicSubscription | Error>
export async function subscribeToFcmTopic(account: GoogleServiceAccountWithoutProjectID, topic: string, ...args: any[]): Promise<FcmTopicSubscription | Error> {
return postFcmTopicsBatchAdd(account, topic, ...args)
}
20 changes: 20 additions & 0 deletions src/functions/unsubscribe-from-fcm-topic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { FcmTopicUnsubscription, GoogleServiceAccountWithoutProjectID } from '../definitions/interfaces.js'
import { postFcmTopicsBatchRemove } from '../requests/fcm-topics-requests.js'

export async function unsubscribeFromFcmTopic(
account: GoogleServiceAccountWithoutProjectID,
topic: string,
...tokens: string[]
): Promise<FcmTopicUnsubscription | Error>
export async function unsubscribeFromFcmTopic(
account: GoogleServiceAccountWithoutProjectID,
topic: string,
tokens: string[]
): Promise<FcmTopicUnsubscription | Error>
export async function unsubscribeFromFcmTopic(
account: GoogleServiceAccountWithoutProjectID,
topic: string,
...args: any[]
): Promise<FcmTopicUnsubscription | Error> {
return postFcmTopicsBatchRemove(account, topic, ...args)
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ export type {
export type { FcmApiMessageWithTarget, FcmApiNotification } from './definitions/types.js'
export * from './functions/register-to-fcm.js'
export * from './functions/send-fcm-message.js'
export * from './functions/subscribe-to-fcm-topic.js'
export * from './functions/subscribe-to-fcm.js'
export * from './functions/unsubscribe-from-fcm-topic.js'
export { ClassLogger as FcmClassLogger } from './loggers/class-logger.js'
export { FunctionLogger as FcmFunctionLogger } from './loggers/function-logger.js'
export { RequestLogger as FcmRequestLogger } from './loggers/request-logger.js'
Expand Down
74 changes: 74 additions & 0 deletions src/requests/fcm-topics-requests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { FcmTopicsAPI } from '../apis/fcm-topics-api.js'
import { FcmTopicsApiDefinitions } from '../definitions/apis/fcm-topics-api-definitions.js'
import { GoogleServiceAccountWithoutProjectID } from '../definitions/interfaces.js'
import { getGoogleAuthAccessToken } from '../utils/google-auth-utils.js'

export async function postFcmTopicsBatchAdd(
account: GoogleServiceAccountWithoutProjectID,
topic: string,
...tokens: string[]
): Promise<FcmTopicsApiDefinitions.BatchAddResponseData | FcmTopicsApiDefinitions.Error>
export async function postFcmTopicsBatchAdd(
account: GoogleServiceAccountWithoutProjectID,
topic: string,
tokens: string[]
): Promise<FcmTopicsApiDefinitions.BatchAddResponseData | FcmTopicsApiDefinitions.Error>
export async function postFcmTopicsBatchAdd(
account: GoogleServiceAccountWithoutProjectID,
topic: string,
...args: any[]
): Promise<FcmTopicsApiDefinitions.BatchAddResponseData | FcmTopicsApiDefinitions.Error> {
let body: FcmTopicsApiDefinitions.BatchAddRequestBody,
headers: HeadersInit,
response: FcmTopicsApiDefinitions.BatchAddResponse | FcmTopicsApiDefinitions.Error

body = {
registration_tokens: args[0] instanceof Array ? args[0] : args,
to: topic.startsWith('/topics/') ? topic : `/topics/${topic}`
}

headers = {
access_token_auth: 'true',
authorization: `Bearer ${await getGoogleAuthAccessToken(account.client_email, account.private_key)}`
}

response = await FcmTopicsAPI.post('iid/v1:batchAdd', body, { headers })
if (response instanceof Error) return response

return response.data
}

export async function postFcmTopicsBatchRemove(
account: GoogleServiceAccountWithoutProjectID,
topic: string,
...tokens: string[]
): Promise<FcmTopicsApiDefinitions.BatchRemoveResponseData | FcmTopicsApiDefinitions.Error>
export async function postFcmTopicsBatchRemove(
account: GoogleServiceAccountWithoutProjectID,
topic: string,
tokens: string[]
): Promise<FcmTopicsApiDefinitions.BatchRemoveResponseData | FcmTopicsApiDefinitions.Error>
export async function postFcmTopicsBatchRemove(
account: GoogleServiceAccountWithoutProjectID,
topic: string,
...args: any[]
): Promise<FcmTopicsApiDefinitions.BatchRemoveResponseData | FcmTopicsApiDefinitions.Error> {
let body: FcmTopicsApiDefinitions.BatchRemoveRequestBody,
headers: HeadersInit,
response: FcmTopicsApiDefinitions.BatchRemoveResponse | FcmTopicsApiDefinitions.Error

body = {
registration_tokens: args[0] instanceof Array ? args[0] : args,
to: topic.startsWith('/topics/') ? topic : `/topics/${topic}`
}

headers = {
access_token_auth: 'true',
authorization: `Bearer ${await getGoogleAuthAccessToken(account.client_email, account.private_key)}`
}

response = await FcmTopicsAPI.post('iid/v1:batchRemove', body, { headers })
if (response instanceof Error) return response

return response.data
}
1 change: 1 addition & 0 deletions tests/definitions/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const ECE_PUBLIC_KEY: Uint8Array = decodeBase64('BD4QIR+mIsck16PMkbQmcfDo
export const FCM_SENDER_ID: string = import.meta.env.VITE_FCM_SENDER_ID
export const FCM_SERVER_KEY: string = import.meta.env.VITE_FCM_SERVER_KEY
export const FCM_TOKEN: string = import.meta.env.VITE_FCM_TOKEN
export const FCM_TOKEN_2: string = import.meta.env.VITE_FCM_TOKEN_2

export const FIREBASE_API_KEY: string = import.meta.env.VITE_FIREBASE_API_KEY
export const FIREBASE_APP_ID: string = import.meta.env.VITE_FIREBASE_APP_ID
Expand Down
1 change: 1 addition & 0 deletions tests/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ interface ImportMetaEnv {
readonly VITE_FCM_SENDER_ID: string
readonly VITE_FCM_SERVER_KEY: string
readonly VITE_FCM_TOKEN: string
readonly VITE_FCM_TOKEN_2: string
readonly VITE_FIREBASE_API_KEY: string
readonly VITE_FIREBASE_APP_ID: string
readonly VITE_FIREBASE_PROJECT_ID: string
Expand Down
24 changes: 24 additions & 0 deletions tests/functions/subscribe-to-fcm-topic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest'
import { subscribeToFcmTopic } from '../../src'
import { FcmTopicSubscription } from '../../src/definitions/interfaces'
import { FCM_TOKEN, FCM_TOKEN_2, GOOGLE_SERVICE_ACCOUNT } from '../definitions/constants'

describe('subscribeToFcmTopic', () => {
it('subscribes single token', async () => {
let subscription: FcmTopicSubscription | Error

subscription = await subscribeToFcmTopic(GOOGLE_SERVICE_ACCOUNT, 'museum', FCM_TOKEN)
if (subscription instanceof Error) throw subscription

expect(subscription.results).toHaveLength(1)
})

it('subscribes multiple tokens', async () => {
let subscription: FcmTopicSubscription | Error

subscription = await subscribeToFcmTopic(GOOGLE_SERVICE_ACCOUNT, 'museum', [FCM_TOKEN, FCM_TOKEN_2])
if (subscription instanceof Error) throw subscription

expect(subscription.results).toHaveLength(2)
})
})
24 changes: 24 additions & 0 deletions tests/functions/unsubscribe-from-fcm-topic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest'
import { unsubscribeFromFcmTopic } from '../../src'
import { FcmTopicUnsubscription } from '../../src/definitions/interfaces'
import { FCM_TOKEN, FCM_TOKEN_2, GOOGLE_SERVICE_ACCOUNT } from '../definitions/constants'

describe('unsubscribeFromFcmTopic', () => {
it('unsubscribes single token', async () => {
let unsubscription: FcmTopicUnsubscription | Error

unsubscription = await unsubscribeFromFcmTopic(GOOGLE_SERVICE_ACCOUNT, 'museum', FCM_TOKEN)
if (unsubscription instanceof Error) throw unsubscription

expect(unsubscription.results).toHaveLength(1)
})

it('unsubscribes multiple tokens', async () => {
let unsubscription: FcmTopicUnsubscription | Error

unsubscription = await unsubscribeFromFcmTopic(GOOGLE_SERVICE_ACCOUNT, 'museum', [FCM_TOKEN, FCM_TOKEN_2])
if (unsubscription instanceof Error) throw unsubscription

expect(unsubscription.results).toHaveLength(2)
})
})
42 changes: 42 additions & 0 deletions tests/requests/fcm-topics-requests.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest'
import { FcmTopicsApiDefinitions } from '../../src/definitions/apis/fcm-topics-api-definitions'
import { postFcmTopicsBatchAdd, postFcmTopicsBatchRemove } from '../../src/requests/fcm-topics-requests'
import { FCM_TOKEN, FCM_TOKEN_2, GOOGLE_SERVICE_ACCOUNT } from '../definitions/constants'

describe('FCM Topics Requests', () => {
it('adds single token', async () => {
let add: FcmTopicsApiDefinitions.BatchAddResponseData | FcmTopicsApiDefinitions.Error

add = await postFcmTopicsBatchAdd(GOOGLE_SERVICE_ACCOUNT, 'museum', FCM_TOKEN)
if (add instanceof Error) throw add

expect(add.results).toHaveLength(1)
})

it('adds multiple tokens', async () => {
let add: FcmTopicsApiDefinitions.BatchAddResponseData | FcmTopicsApiDefinitions.Error

add = await postFcmTopicsBatchAdd(GOOGLE_SERVICE_ACCOUNT, 'museum', [FCM_TOKEN, FCM_TOKEN_2])
if (add instanceof Error) throw add

expect(add.results).toHaveLength(2)
})

it('removes single token', async () => {
let remove: FcmTopicsApiDefinitions.BatchRemoveResponseData | FcmTopicsApiDefinitions.Error

remove = await postFcmTopicsBatchRemove(GOOGLE_SERVICE_ACCOUNT, 'museum', FCM_TOKEN)
if (remove instanceof Error) throw remove

expect(remove.results).toHaveLength(1)
})

it('removes multiple tokens', async () => {
let remove: FcmTopicsApiDefinitions.BatchRemoveResponseData | FcmTopicsApiDefinitions.Error

remove = await postFcmTopicsBatchRemove(GOOGLE_SERVICE_ACCOUNT, 'museum', [FCM_TOKEN, FCM_TOKEN_2])
if (remove instanceof Error) throw remove

expect(remove.results).toHaveLength(2)
})
})
Loading