bởi Jaxon C.

A Node.js server SDK for OneSignal that enables sending push notifications, emails, and SMS at scale with full API coverage. Ideal for backend services needing personalized multi-channel messaging.
This block is the official OneSignal Node.js server SDK (@onesignal/node-onesignal@5.5.0), providing typed access to the OneSignal REST API for sending push notifications, emails, and SMS messages. It targets backend Node.js or TypeScript services that need programmatic control over notifications, user segments, apps, and subscription management.
.github/ - CI/CD workflows and issue templatesapis/ - DefaultApi implementation plus base class and exception typesauth/ - API key authentication method configurationhttp/ - HTTP request/response abstractions and isomorphic fetch adaptermodels/ - All typed model classes (Notification, App, Segment, etc.)types/ - Promise-based API wrappersconfiguration.ts - createConfiguration factory and ConfigurationParameters interfaceindex.ts - Root barrel export for the entire SDKmiddleware.ts - Middleware and PromiseMiddleware interfaces for request/response interceptionservers.ts - ServerConfiguration class and the default server1 endpointutil.ts - Internal helpers (isCodeInRange, canConsumeForm)rxjsStub.ts - Minimal RxJS shim used internallypackage.json - Package metadata and runtime dependenciestsconfig.json - TypeScript compiler settings for the SDKnpm install @onesignal/node-onesignal btoa es6-promise form-data url-parse
No native modules, no pod installs, no Android linking, and no prebuild steps are required. This is a pure Node.js package.
Copy the source directory into your project, e.g. src/onesignal/ or keep it as source/ at the repo root. The path you choose becomes the import base.
Configure tsconfig.json to include the source and set a path alias if desired:
{
"compilerOptions": {
"paths": {
"@onesignal/*": ["./source/*"]
},
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true
},
"include": ["src/**/*", "source/**/*"]
}
Khởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This TypeScript cli / script completed archive review with strong static results. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Quy trình avcp-2026-08-04.1 · SHA-256 b571f77aa804719e…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
Set environment variables — never hard-code keys:
ONESIGNAL_REST_API_KEY=your_rest_api_key
ONESIGNAL_ORG_API_KEY=your_org_api_key
ONESIGNAL_APP_ID=your_app_id
Create a shared client module (e.g. src/onesignalClient.ts):
import { createConfiguration, DefaultApi } from '../source/index';
export const configuration = createConfiguration({
restApiKey: process.env.ONESIGNAL_REST_API_KEY!,
organizationApiKey: process.env.ONESIGNAL_ORG_API_KEY,
});
export const client = new DefaultApi(configuration);
Ensure fetch is available in Node < 18 by polyfilling:
import 'es6-promise/auto';
// node-fetch or cross-fetch if needed for older Node versions
createConfigurationfunction createConfiguration(conf: ConfigurationParameters): Configuration;
Factory that builds a Configuration object from partial parameters. Pass restApiKey for most endpoints or organizationApiKey for org-level operations. Defaults: baseServer = server1 (https://api.onesignal.com), empty middleware array, isomorphic fetch HTTP adapter.
DefaultApiclass DefaultApi {
constructor(configuration: Configuration);
createNotification(notification: Notification): Promise<CreateNotificationSuccessResponse>;
getNotification(appId: string, notificationId: string): Promise<NotificationWithMeta>;
getApp(appId: string): Promise<App>;
// ...many more endpoints; see DefaultApi.md
}
The primary API client. Instantiate it with a Configuration and call its methods to interact with every OneSignal REST endpoint. All methods return Promises.
Middleware / PromiseMiddlewareinterface PromiseMiddleware {
pre(context: RequestContext): Promise<RequestContext>;
post(context: ResponseContext): Promise<ResponseContext>;
}
Use these interfaces to intercept outgoing requests (e.g. to log, mutate headers) or incoming responses (e.g. to log errors, transform payloads). Pass instances via ConfigurationParameters.promiseMiddleware.
Create a Notification model, set the required fields, and call createNotification. The response includes the OneSignal notification ID for tracking.
import { createConfiguration, DefaultApi, Notification } from '../source/index';
const config = createConfiguration({
restApiKey: process.env.ONESIGNAL_REST_API_KEY!,
});
const client = new DefaultApi(config);
async function sendPush(): Promise<void> {
const notification = new Notification();
notification.app_id = process.env.ONESIGNAL_APP_ID!;
notification.contents = { en: 'Hello from the server!' };
notification.headings = { en: 'New Alert' };
notification.included_segments = ['Subscribed Users'];
const response = await client.createNotification(notification);
console.log('Created notification ID:', response.id);
}
sendPush().catch(console.error);
Register a custom PromiseMiddleware to inspect the RequestContext before every API call — useful for debugging or auditing.
import {
createConfiguration,
DefaultApi,
Notification,
} from '../source/index';
import { PromiseMiddleware } from '../source/middleware';
import { RequestContext, ResponseContext } from '../source/http/http';
const loggingMiddleware: PromiseMiddleware = {
async pre(context: RequestContext): Promise<RequestContext> {
console.log(`[PRE] ${context.getHttpMethod()} ${context.getUrl()}`);
return context;
},
async post(context: ResponseContext): Promise<ResponseContext> {
console.log(`[POST] status: ${context.httpStatusCode}`);
return context;
},
};
const config = createConfiguration({
restApiKey: process.env.ONESIGNAL_REST_API_KEY!,
promiseMiddleware: [loggingMiddleware],
});
const client = new DefaultApi(config);
const n = new Notification();
n.app_id = process.env.ONESIGNAL_APP_ID!;
n.contents = { en: 'Middleware test' };
n.included_segments = ['Test Users'];
client.createNotification(n).then(r => console.log(r.id));
Use the same Notification model but set email_subject, email_body, and channel_for_external_user_ids to target the email channel.
import { createConfiguration, DefaultApi, Notification } from '../source/index';
const config = createConfiguration({
restApiKey: process.env.ONESIGNAL_REST_API_KEY!,
});
const client = new DefaultApi(config);
async function sendEmail(): Promise<void> {
const notification = new Notification();
notification.app_id = process.env.ONESIGNAL_APP_ID!;
notification.email_subject = 'Your weekly digest';
notification.email_body = '<h1>Hello!</h1><p>Here is your update.</p>';
notification.included_segments = ['Subscribed Users'];
notification.channel_for_external_user_ids = 'email';
const response = await client.createNotification(notification);
console.log('Email notification ID:', response.id);
}
sendEmail().catch(console.error);
index.ts - Barrel file; re-exports everything the consumer needs (DefaultApi, Notification, createConfiguration, Middleware, etc.).configuration.ts - Defines ConfigurationParameters, Configuration interface, and the createConfiguration factory that merges auth, server, and middleware settings.middleware.ts - Declares the Middleware (Observable-based) and PromiseMiddleware interfaces; provides PromiseMiddlewareWrapper to bridge them.servers.ts - ServerConfiguration generic class for URL template resolution; exports server1 (https://api.onesignal.com) as the default.util.ts - Two pure utility functions (isCodeInRange, canConsumeForm) used internally by generated API code.rxjsStub.ts - Minimal Observable/from shim so the SDK does not require a full RxJS dependency.apis/DefaultApi.ts - All REST endpoint implementations as class methods returning Promises.apis/baseapi.ts - Abstract base class for generated API classes; exports RequiredError.apis/exception.ts - ApiException class thrown on non-2xx responses.auth/auth.ts - configureAuthMethods and supporting types for REST API key and Organization API key schemes.http/http.ts - RequestContext, ResponseContext, HttpLibrary interface, and HttpMethod enum.http/isomorphic-fetch.ts - Default HttpLibrary implementation using the global fetch.models/ - One file per model (e.g. Notification.ts, App.ts); plus ObjectSerializer.ts for (de)serialization.types/ - Promise-based API wrappers generated from the Observable-based core; PromiseDefaultApi is exported as DefaultApi.fetch in Node < 18 — install node-fetch and assign global.fetch = require('node-fetch') before importing the SDK, or use --experimental-fetch on Node 17.btoa not defined — the SDK depends on btoa; in Node < 16 add global.btoa = (str) => Buffer.from(str).toString('base64') at your entry point.restApiKey vs organizationApiKey confusion — most app-level endpoints (notifications, users) require restApiKey; org-level endpoints (create/list apps) require organizationApiKey. Passing the wrong key returns a 401 that looks like a network error."type": "module", the SDK ships CommonJS; wrap imports with createRequire or set "moduleResolution": "bundler" in tsconfig and use a bundler like esbuild.ApiException not caught — the SDK throws ApiException (from apis/exception.ts) on HTTP errors; catch it explicitly: catch (e) { if (e instanceof ApiException) ... }.paths to tsconfig, also configure tsconfig-paths or tsc-alias so compiled JS resolves the aliases; otherwise module not found errors appear at runtime.I have the OneSignal Node.js Server SDK source code located in `source/` and
its integration guide at `USAGE.md`. The upstream package is
`@onesignal/node-onesignal@5.5.0`.
Please integrate the SDK into my existing project step by step:
1. Read `USAGE.md` in full for correct import paths, types, and examples.
2. Install all required dependencies listed in the "Required dependencies" section.
3. Create a shared client module at `src/onesignalClient.ts` that reads API
keys from environment variables and exports a configured `DefaultApi` instance.
4. Add a utility function `sendPushNotification(appId, contents, segments)` that
uses the shared client to call `client.createNotification(...)` and returns
the notification ID.
5. Add error handling that catches `ApiException` (from `source/apis/exception`)
and logs the HTTP status code and body.
6. Show me the final file tree of modified/added files.
Do not invent any API methods or types. Only use exports visible in
`source/index.ts` and documented in `USAGE.md`.
The source is licensed under the MIT License — see source/LICENSE for the full text. Upstream package: @onesignal/node-onesignal by OneSignal, Inc. Repository: github.com/OneSignal/node-onesignal.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
WordPress & WooCommerce Plugins
Miễn phí