Azure Notification Hubs는 백 엔드(클라우드 또는 온-프레미스)에서 모든 플랫폼(Apple, Amazon Kindle, Firebase, Baidu, Xiaomi, 웹, Windows 등)으로 알림을 보낼 수 있는 스케일 아웃 푸시 엔진을 제공합니다. Notification Hubs는 엔터프라이즈 및 소비자 시나리오 모두에서 잘 작동합니다. 다음은 몇 가지 예제 시나리오입니다.
- 짧은 대기 시간으로 수백만 명에게 속보 알림을 보냅니다.
- 관심 있는 사용자 세그먼트에 위치 기반 쿠폰을 보냅니다.
- 미디어/스포츠/금융/게임 애플리케이션에 대한 사용자 또는 그룹에 이벤트 관련 알림을 보냅니다.
- 프로모션 콘텐츠를 애플리케이션에 푸시하여 고객의 참여를 유도하고 마케팅합니다.
- 새 메시지 및 작업 항목과 같은 엔터프라이즈 이벤트를 사용자에게 알립니다.
- 다단계 인증을 위한 코드를 보냅니다.
키 링크:
참고: 패키지를 azure-sb 사용하는 경우 migration guide to move from azure-sb to @azure/notification-hubs
시작하기
현재 지원되는 환경
- Node.js의 LTS 버전
- Safari, Chrome, Edge 및 Firefox의 최신 버전입니다.
자세한 내용은 지원 정책을 참조하세요.
패키지 설치
npm install @azure/notification-hubs
필수 조건
Azure Notification Hubs 리소스 만들기
Azure 알림 허브는 다음 방법을 사용하여 만들 수 있습니다.
알림 허브를 만든 후에는 Azure Portal 또는 Azure CLI를 사용하여 구성할 수 있습니다.
클라이언트 가져오기
이 JavaScript용 SDK는 클래스 기반 접근 방식 또는 모듈식 디자인 접근 방식을 통해 Azure Notification Hubs와 상호 작용하는 두 가지 방법을 제공합니다. 클래스 기반 접근 방식은 클라이언트를 만든 다음 클라이언트의 메서드와 상호 작용하기 위해 모든 패키지에서 일관됩니다.
import { NotificationHubsClient, createAppleInstallation } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const installation = createAppleInstallation({
installationId: "<installation-id>",
pushChannel: "<push-channel>",
tags: ["likes_javascript"],
});
const result = await client.createOrUpdateInstallation(installation);
모듈식 접근 방식을 통해 개발자는 각 메서드가 개별적으로 노출될 때 가져올 함수를 선택할 수 있습니다. 이 접근 방식은 ES-Modules와 함께 하위 경로 내보내기를 사용하여 직접 가져오기를 통해 메서드를 노출합니다. 개별 내보내기를 사용하면 개발자가 활용할 수 있는 더 나은 트리 쉐이킹 경험과 더 작은 번들 크기를 만들 수 있습니다.
클라이언트 만들기는 하위 경로를 통해 "@azure/notification-hubs/api" 노출되고 모든 클라이언트 메서드는 하위 경로를 통해 "@azure/notification-hubs/api" 노출됩니다. 내보낸 각 함수는 첫 client 번째 매개변수로 사용되며 나머지 매개변수는 변경되지 않습니다.
다음 하위 경로가 노출됩니다.
-
@azure/notification-hubs/api- 클라이언트 viacreateClientContext및 클라이언트 메서드(예:getInstallation또는sendNotification -
@azure/notification-hubs/models- Notification Hubs 모델 및 팩터리 메서드입니다.
위의 코드 조각은 다음과 같습니다.
import { createClientContext, createOrUpdateInstallation } from "@azure/notification-hubs/api";
import { createAppleInstallation } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const installation = createAppleInstallation({
installationId: "<installation-id>",
pushChannel: "<push-channel>",
tags: ["likes_javascript"],
});
const result = await createOrUpdateInstallation(context, installation);
클라이언트 인증
Azure 알림 허브와의 상호 작용은 공유 액세스 서명 연결 문자열을 지원하는 것으로 NotificationHubsClient 시작됩니다. 여기에는 수신기, 관리, 보내기 권한 수준이 포함됩니다.
Listen을 사용하면 클라이언트가 등록 및 설치 API를 통해 자신을 등록할 수 있습니다. 보내기를 사용하면 클라이언트가 보내기 API를 사용하여 장치에 알림을 보낼 수 있습니다. 마지막으로 관리를 통해 사용자는 쿼리와 같은 등록 및 설치 관리를 수행할 수 있습니다.
연결 문자열 및 알림 허브 이름이 있는 생성자를 사용하여 새 NotificationHubsClient 클라이언트를 만들 수 있습니다.
import { NotificationHubsClient } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
모듈식 접근 방식을 사용하면 하위 경로를 통해 "@azure/notification-hubs/api" 가져올 createClientContext 수 있습니다.
import { createClientContext } from "@azure/notification-hubs/api";
const context = createClientContext("<connection string>", "<hub name>");
주요 개념
초기화 NotificationHubClient 되면 다음 개념을 살펴볼 수 있습니다.
- 설치 및 등록을 통한 장치 관리 설명
- 장치에 알림 보내기
디바이스 관리
장치 관리는 APN 또는 Firebase와 같은 네이티브 PNS(플랫폼 알림 서비스)의 고유 식별자와 대상 그룹에 푸시 알림을 보내는 데 사용되는 태그와 같은 관련 메타데이터를 저장할 수 있는 Notification Hubs의 핵심 개념입니다. 이 작업은 두 개의 API, 즉 최신 기본 메커니즘인 설치 API와 등록을 사용하여 수행됩니다.
설치 API
설치는 대상 그룹에 보내는 데 사용할 수 있는 설치 ID 및 사용자 ID와 같은 추가 속성을 포함하는 장치 관리에 대한 최신 기본 JSON 접근 방식입니다. 설치 API는 다음과 같은 방식으로 기존 등록 API에 비해 몇 가지 장점이 있습니다.
- 완전히 멱등성 API이므로 설치 시 create를 호출하므로 중복에 대한 걱정 없이 작업을 다시 시도할 수 있습니다.
- 및 와 같은
$UserId:{bob@contoso.com}$InstallationId:{myInstallId}태그 표현식에서 사용할 수 있는 속성에 대한userIdinstallationId지원 및 . - 템플릿은 이제 별도의 등록 대신 설치의 일부이며 이름으로 전송용 태그로 참조할 수 있습니다.
- 부분 업데이트는 JSON 패치 표준을 통해 지원되며, 이를 통해 설치를 먼저 쿼리하지 않고도 태그를 추가하고 다른 데이터를 변경할 수 있습니다.
설치는 다음과 같은 방법을 통해 createOrUpdateInstallation 만들 수 있습니다.
import { NotificationHubsClient, createAppleInstallation } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
// Create an installation for APNs
const installation = createAppleInstallation({
installationId: "0d8ab095-c449-493f-9195-17e4917806c4", // Must be unique
pushChannel: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0", // PNS specific handle
tags: ["likes_hockey", "likes_football"],
});
const response = await client.createOrUpdateInstallation(installation);
모듈식 접근 방식을 사용하면 코드는 다음과 같습니다.
import { createClientContext, createOrUpdateInstallation } from "@azure/notification-hubs/api";
import { createAppleInstallation } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
// Create an installation for APNs
const installation = createAppleInstallation({
installationId: "0d8ab095-c449-493f-9195-17e4917806c4", // Must be unique
pushChannel: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0", // PNS specific handle
tags: ["likes_hockey", "likes_football"],
});
const response = await createOrUpdateInstallation(context, installation);
메서드를 사용하여 updateInstallation 태그 및 사용자 ID를 추가하는 것과 같은 JSON 패치 스키마를 통해 설치를 업데이트할 수 있습니다.
import { NotificationHubsClient, JsonPatch } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const installationId = "<unique installation ID>";
const updates: JsonPatch[] = [
{ op: "add", path: "/tags", value: "likes_baseball" },
{ op: "add", path: "/userId", value: "bob@contoso.com" },
];
const installation = await client.updateInstallation(installationId, updates);
모듈식 접근 방식을 사용하면 코드는 다음과 같습니다.
import { createClientContext, updateInstallation } from "@azure/notification-hubs/api";
import { JsonPatch } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const installationId = "<unique installation ID>";
const updates: JsonPatch[] = [
{ op: "add", path: "/tags", value: "likes_baseball" },
{ op: "add", path: "/userId", value: "bob@contoso.com" },
];
const installation = await updateInstallation(context, installationId, updates);
기존 설치를 검색하려면 기존 고유 설치 ID와 함께 메서드를 getInstallation 사용합니다.
import { NotificationHubsClient } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const installationId = "<unique installation ID>";
const installation = client.getInstallation(installationId);
모듈식 접근 방식을 사용하면 코드는 다음과 같습니다.
import { createClientContext, getInstallation } from "@azure/notification-hubs/api";
const context = createClientContext("<connection string>", "<hub name>");
const installationId = "<unique installation ID>";
const installation = getInstallation(context, installationId);
등록 API
등록은 위의 설치와 마찬가지로 PNS의 고유 디바이스 식별자 및 관련 태그와 함께 PNS와 연결됩니다. 템플릿 등록은 미리 정의된 본문 템플릿을 만드는 방법으로, 메시지를 채울 속성을 사용하여 전송 시 사용자 지정할 수 있습니다. 템플릿에 대한 자세한 내용은 템플릿 설명서를 참조하세요.
설치는 두 가지 방법 중 하나로 만들 수 있으며, 먼저 를 사용하여 getInstallationId 서버에서 등록 ID를 가져온 다음 createOrUpdateRegistration 또는 메서드를 통해 만듭니다.createRegistration
import {
NotificationHubsClient,
createAppleRegistrationDescription,
} from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const registration = createAppleRegistrationDescription({
deviceToken: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0",
tags: ["likes_hockey", "likes_football"],
});
const updatedRegistration = await client.createRegistration(registration);
모듈식 접근 방식을 사용하면 코드는 다음과 같습니다.
import { createClientContext, createRegistration } from "@azure/notification-hubs/api";
import { createAppleRegistrationDescription } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const registration = createAppleRegistrationDescription({
deviceToken: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0",
tags: ["likes_hockey", "likes_football"],
});
const updatedRegistration = await createRegistration(context, registration);
이 메서드를 updateRegistration 통해 업데이트를 수행할 수 있지만 설치와 달리 증분 업데이트를 지원하지 않습니다. 기존 등록에 대한 쿼리는 메서드를 getRegistration 사용하여 수행할 수 있습니다.
import { NotificationHubsClient } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const registrationId = "<unique Registration ID>";
const registration = await client.getRegistration(registrationId);
if (registration.tags) {
registration.tags.push("likes_sports");
} else {
registration.tags = ["likes_sports"];
}
const updatedRegistration = await client.updateRegistration(registration);
모듈식 접근 방식을 사용하면 코드는 다음과 같습니다.
import {
createClientContext,
getRegistration,
updateRegistration,
} from "@azure/notification-hubs/api";
const context = createClientContext("<connection string>", "<hub name>");
const registrationId = "<unique Registration ID>";
const registration = await getRegistration(context, registrationId);
if (registration.tags) {
registration.tags.push("likes_sports");
} else {
registration.tags = ["likes_sports"];
}
const updatedRegistration = await updateRegistration(context, registration);
설치와 달리 등록을 쿼리하여 모든 등록을 가져오거나 등록을 조건과 일치시키거나 태그로 확인할 수 있습니다. 등록은 , listRegistrationsByChannel 및 listRegistrationsByTag 메서드를 사용하여 listRegistrations쿼리할 수 있습니다. 모든 메서드는 옵션을 통한 top 제한을 지원하고 비동기 페이징을 지원합니다.
import { NotificationHubsClient } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const registrations = client.listRegistrationsByTag("likes_hockey");
let page = 0;
for await (const pages of registrations.byPage()) {
console.log(`Page number ${page++}`);
for (const item of pages) {
console.log(JSON.stringify(item, null, 2));
}
}
모듈식 접근 방식을 사용하면 코드는 다음과 같습니다.
import { createClientContext, listRegistrationsByTag } from "@azure/notification-hubs/api";
const context = createClientContext("<connection string>", "<hub name>");
const registrations = await listRegistrationsByTag(context, "likes_hockey");
let page = 0;
for await (const pages of registrations.byPage()) {
console.log(`Page number ${page++}`);
for (const item of pages) {
console.log(JSON.stringify(item, null, 2));
}
}
보내기 작업
Notification Hubs는 고유한 PNS 제공 식별자를 사용하여 직접 디바이스에 알림을 보내거나, 대상 그룹 보내기에 태그를 사용하거나, 모든 디바이스에 대한 일반 브로드캐스트를 지원합니다. 표준 SKU 이상을 사용하면 예약된 전송 을 통해 사용자가 최대 7일 전에 알림을 예약할 수 있습니다. 모든 송신 작업은 Notification Hubs 지원 사례에 사용할 수 있는 추적 ID 및 상관 관계 ID를 반환합니다. 표준 SKU 이상에서는 메서드를 통해 getNotificationOutcomeDetails 알림 원격 분석을 가져오는 데 사용할 수 있는 알림 ID도 반환됩니다.
디버깅을 위해 enableTestSend 메서드에 대한 sendNotification PNS에서 즉각적인 피드백을 가져오는 옵션을 설정할 true 수 있지만 프로덕션 시나리오에서는 지원되지 않습니다. 예약된 전송 방법에서는 지원되지 않습니다.
원시 JSON 또는 XML 문자열을 보내기 또는 예약된 보내기 메서드로 보내거나 APN, Firebase, Baidu, ADM 및 WNS와 같은 PNS별로 메시지를 생성하는 데 도움이 되는 알림 작성기를 사용할 수 있습니다. 이러한 빌더는 기본 메시지 형식을 작성하므로 각 PNS에 사용할 수 있는 필드를 추측할 필요가 없습니다.
import { createAppleNotificationBody, createAppleNotification } from "@azure/notification-hubs";
const apnsBody = createAppleNotificationBody({
alert: {
title: "Notification Title",
subtitle: "Notification Subtitle",
body: "Notification body goes here",
},
sound: "default",
interruptionLevel: "time-sensitive",
});
// Send the message using the modular approach
const notification = createAppleNotification({
body: apnsBody,
});
브로드캐스트 전송
Notification Hubs를 사용하여 메서드를 통해 sendBroadcastNotification 브로드캐스트 전송을 사용하여 플랫폼당 등록된 모든 디바이스에 알림을 보낼 수 있습니다.
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await client.sendBroadcastNotification(message);
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
모듈식 접근 방식을 사용하면 코드는 다음과 같습니다.
import { createClientContext, sendBroadcastNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await sendBroadcastNotification(context, message);
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
직접 전송
장치를 직접 보내려면 사용자는 매개 변수와 함께 메서드를 sendNotification 호출하여 APNs 장치 토큰과 같은 플랫폼에서 제공하는 고유 식별자를 사용하여 보낼 수 있습니다 deviceHandle .
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const deviceHandle = "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await client.sendNotification(message, { deviceHandle });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
모듈식 접근 방식을 사용하면 코드는 다음과 같습니다.
import { createClientContext, sendNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const deviceHandle = "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await sendNotification(context, message, { deviceHandle });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
청중 보내기
사용자는 단일 기기를 타겟팅하는 것 외에도 태그를 사용하여 여러 기기를 타겟팅할 수 있습니다. 이러한 태그는 태그 목록으로 제공되며, 이 태그는 등록된 장치와 일치하는 태그 표현식을 만들거나, 부울 논리를 사용하여 올바른 대상을 타겟팅할 수 있는 태그 표현식을 통해 제공될 수 있습니다. 태그 및 태그 표현식에 대한 자세한 내용은 라우팅 및 태그 표현식 단원을 참조하십시오.
태그 배열에서 태그 표현식을 생성하려는 경우 태그에서 "또는 태그 표현식"을 생성하는 최상위 가져오기 또는 @azure/notification-hubs/models/tagExpressionBuilder 모듈식 가져오기에 노출되는 메서드와 함께 createTagExpression 사용할 수 있는 태그 표현식 빌더가 있습니다.
import { createTagExpression } from "@azure/notification-hubs";
const tags = ["likes_football", "likes_hockey"];
const tagExpression = createTagExpression(tags);
console.log(tagExpression);
태그 표현식 메시지는 다음 코드를 사용하여 보낼 수 있습니다.
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const notification = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await client.sendNotification(notification, { tagExpression });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
모듈식 접근 방식을 사용하면 코드는 다음과 같습니다.
import { createClientContext, sendNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const notification = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await sendNotification(context, notification, { tagExpression });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
예약된 전송
푸시 알림은 태그가 있는 디바이스로 보내는 방법 또는 일반 브로드캐스트scheduleBroadcastNotification를 사용하여 scheduleNotification 표준 SKU 네임스페이스 이상에서 최대 7일 전에 예약할 수 있습니다. 그러면 메서드를 통해 필요한 경우 취소하는 데 사용할 수 있는 알림 ID가 반환됩니다.cancelScheduledNotification
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
// Schedule 8 hours from now
const scheduledTime = new Date(Date.now() + 8 * 60 * 60 * 1000);
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await client.scheduleNotification(scheduledTime, message, { tagExpression });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Can be used to cancel via the cancelScheduledSend method
console.log(`Notification ID: ${result.notificationId}`);
모듈식 접근 방식을 사용하면 코드는 다음과 같습니다.
import { createClientContext, scheduleNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
// Schedule 8 hours from now
const scheduledTime = new Date(Date.now() + 8 * 60 * 60 * 1000);
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await scheduleNotification(context, scheduledTime, message, { tagExpression });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Can be used to cancel via the cancelScheduledSend method
console.log(`Notification ID: ${result.notificationId}`);
Troubleshooting
React Native 지원
React Native는 현재 Azure Notification Hubs SDK에서 사용하는 [URLSearchParams]를 지원하지 않습니다. React Native에서 SDK를 사용하려면 SDK를 사용하기 전에 패키지를 url-search-params-polyfill 설치하고 가져와야 합니다.
또한 API 및 비동기 반복자 API에 대한 TextEncoder 폴리필을 제공해야 합니다. 자세한 내용은 Expo가 포함된 React Native 샘플 을 참조하세요.
삭제된 알림 진단
Azure Notification Hubs에는 Azure Notification Hubs에서 삭제된 알림 진단 가이드에서 삭제된 알림 문제를 해결하는 방법에 대한 전체 가이드가 있습니다.
테스트 전송은 다음 옵션을 사용하여 및 sendBroadcastNotification 메서드에서 sendNotification 지원됩니다.enableTestSend
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const notification = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await client.sendNotification(notification, {
tagExpression,
enableTestSend: true,
});
import { createClientContext, sendNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const notification = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await sendNotification(context, notification, {
tagExpression,
enableTestSend: true,
});
로깅 (로그 기록)
로깅을 사용하도록 설정하면 오류에 대한 유용한 정보를 파악하는 데 도움이 될 수 있습니다. HTTP 요청 및 응답 로그를 보려면 AZURE_LOG_LEVEL 환경 변수를 info설정합니다. 또는 setLogLevel@azure/logger 호출하여 런타임에 로깅을 사용하도록 설정할 수 있습니다.
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
로그를 사용하도록 설정하는 방법에 대한 자세한 지침은 @azure/로거 패키지 문서를 참조하세요.
다음 단계
다음 샘플에서는 Azure Notification Hubs와 상호 작용할 수 있는 다양한 방법을 보여 줍니다.
장치 관리:
- 설치 API
- 등록 API
전송 작업:
관리 운영:
Contributing
이 라이브러리에 기여하려면 기여 가이드 를 참조하여 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.
이 모듈의 테스트는 라이브 테스트와 단위 테스트가 혼합되어 있으며, Azure Notification Hubs 인스턴스가 있어야 합니다. 테스트를 실행하려면 다음을 실행해야 합니다.
pnpm installpnpm build --filter @azure/notification-hubs...- 폴더에 다음 내용이 포함된 .env 파일을 만듭니다.
sdk\notificationhubs\notification-hubsNOTIFICATIONHUBS_CONNECTION_STRING=connection string for your Notification Hubs instanceNOTIFICATION_HUB_NAME=Notification Hub name cd sdk\notificationhubs\notification-hubs-
npm run test;
자세한 내용은 테스트 폴더를 참조하십시오.
관련 프로젝트
- JavaScript용 Microsoft Azure SDK
- Azure Notification Hubs
Azure SDK for JavaScript