Skip to content

Commit

Permalink
refactor: rename notification -> message
Browse files Browse the repository at this point in the history
  • Loading branch information
maxholman committed Apr 23, 2023
1 parent 68bbfec commit 31a183b
Show file tree
Hide file tree
Showing 8 changed files with 31 additions and 35 deletions.
11 changes: 5 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ pnpm add @block65/webcrypto-web-push
```typescript
import {
type PushSubscription,
type Notification,
type PushMessage,
type VapidKeys
sendPushNotification,
buildPushPayload,
} from '@block65/webcrypto-web-push';

const vapid: VapidKeys = {
Expand All @@ -33,7 +33,6 @@ const vapid: VapidKeys = {
privateKey: env.VAPID_SERVER_PRIVATE_KEY,
};

// You would probably get a subscription object from the datastore
const subscription: PushSubscription = {
endpoint: 'https://fcm.googleapis.com/fcm/send/...',
expirationTime: null,
Expand All @@ -43,15 +42,15 @@ const subscription: PushSubscription = {
},
};

const notification: Notification = {
body: 'You have a new message!',
const message: PushMessage = {
body: "You've got mail!",
options: {
ttl: 60,
},
};

// send the payload using your favourite fetch library
const init = await buildPushPayload(notification, subscription, vapid);
const init = await buildPushPayload(message, subscription, vapid);
const res = await fetch(subscription.endpoint, init);
```

Expand Down
2 changes: 1 addition & 1 deletion lib/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export type { PushNotification, PushSubscription } from './types.js';
export type { PushMessage, PushSubscription } from './types.js';

export { encryptNotification } from './encrypt.js';

Expand Down
21 changes: 10 additions & 11 deletions lib/payload.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { encodeBase64Url } from './base64.js';
import { encryptNotification } from './encrypt.js';
import type { PushNotification, PushSubscription } from './types.js';
import type { PushMessage, PushSubscription } from './types.js';
import { vapidHeaders, type VapidKeys } from './vapid.js';

export async function buildPushPayload(
notification: PushNotification,
message: PushMessage,
subscription: PushSubscription,
vapid: VapidKeys,
) {
Expand All @@ -14,10 +14,9 @@ export async function buildPushPayload(
subscription,
new TextEncoder().encode(
// if its a primitive, convert to string, otherwise stringify
typeof notification.data === 'string' ||
typeof notification.data === 'number'
? notification.data.toString()
: JSON.stringify(notification.data),
typeof message.data === 'string' || typeof message.data === 'number'
? message.data.toString()
: JSON.stringify(message.data),
),
);

Expand All @@ -31,12 +30,12 @@ export async function buildPushPayload(

encryption: `keyid=p256dh;salt=${encodeBase64Url(encrypted.salt)}`,

ttl: (notification.options?.ttl || 60).toString(),
...(notification.options?.urgency && {
urgency: notification.options.urgency,
ttl: (message.options?.ttl || 60).toString(),
...(message.options?.urgency && {
urgency: message.options.urgency,
}),
...(notification.options?.topic && {
topic: notification.options.topic,
...(message.options?.topic && {
topic: message.options.topic,
}),

'content-encoding': 'aesgcm',
Expand Down
2 changes: 1 addition & 1 deletion lib/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { type Jsonifiable, type RequireAtLeastOne } from 'type-fest';

export interface PushNotification {
export interface PushMessage {
data: Jsonifiable;

options?: RequireAtLeastOne<{
Expand Down
8 changes: 3 additions & 5 deletions src/node.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
/// <reference types="node" />

import { buildPushPayload } from '../lib/main.js';
import { notification, subscription, vapid } from './shared.js';
import { message, subscription, vapid } from './shared.js';

declare let fetch: typeof import('undici').fetch;

const init = await buildPushPayload(notification, subscription, vapid);
const init = await buildPushPayload(message, subscription, vapid);
const res = await fetch(subscription.endpoint, init);

if (res.ok) {
console.log(res.status, res.statusText, await res.text());
} else {
throw new Error(
`Push notification failed. HTTP ${res.status} ${res.statusText}}`,
);
throw new Error(`Push failed. HTTP ${res.status} ${res.statusText}}`);
}
6 changes: 3 additions & 3 deletions src/shared.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {
type PushNotification,
type PushMessage,
type PushSubscription,
type VapidKeys,
} from '../lib/main.js';
Expand All @@ -22,8 +22,8 @@ export const subscription: PushSubscription = {
},
};

export const notification: PushNotification = {
data: 'You have a new message!',
export const message: PushMessage = {
data: "You've got mail!",
options: {
ttl: 60,
},
Expand Down
10 changes: 5 additions & 5 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// <reference types="@cloudflare/workers-types" />
import { buildPushPayload } from '../lib/main.js';
import { notification, subscription, vapid } from './shared.js';
import { message, subscription, vapid } from './shared.js';

interface Env {
VAPID_SUBJECT: string;
Expand All @@ -11,22 +11,22 @@ interface Env {
export default {
fetch: async function handleRequest() {
try {
const init = await buildPushPayload(notification, subscription, vapid);
const init = await buildPushPayload(message, subscription, vapid);

const res = await fetch(subscription.endpoint, init);

if (res.ok) {
return new Response(
`Push notification sent successfully! HTTP ${res.status} ${res.statusText}}`,
`Push message sent successfully! HTTP ${res.status} ${res.statusText}}`,
);
}

return new Response(
`Push notification failed. HTTP ${res.status} ${res.statusText}}`,
`Push message send failed. HTTP ${res.status} ${res.statusText}}`,
);
} catch (err) {
console.error(err);
return new Response('Failed to send push notification.', { status: 500 });
return new Response('Failed to send push message.', { status: 500 });
}
},
} satisfies ExportedHandler<Env>;
6 changes: 3 additions & 3 deletions test/push.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { describe, expect, test } from 'vitest';
import { buildPushPayload } from '../lib/main.js';
import { type PushNotification } from '../lib/types.js';
import { type PushMessage } from '../lib/types.js';
import { fakeSubscriptions, fakeVapid } from './fixtures.js';

describe('Payload', () => {
test('Fake Subscription', async () => {
const notification: PushNotification = {
const message: PushMessage = {
data: 'Some text',
options: {
ttl: 60,
Expand All @@ -18,7 +18,7 @@ describe('Payload', () => {

const subscription = fakeSubscriptions.test;

const init = await buildPushPayload(notification, subscription, fakeVapid);
const init = await buildPushPayload(message, subscription, fakeVapid);
const res = await fetch(subscription.endpoint, init);

await expect(res.text()).resolves.toMatchInlineSnapshot('""');
Expand Down

0 comments on commit 31a183b

Please sign in to comment.