Code Monkey home page Code Monkey logo

onesignal-node-api's Introduction

Welcome to @onesignal/node-onesignal ๐Ÿ‘‹

Version Documentation Maintenance Twitter: onesignal

OpenAPI client for node-onesignal

๐Ÿ  Homepage

๐Ÿ–ค npm

Node Client SDK

The OneSignal Node client is a server OneSignal SDK for NodeJS. Integrate OneSignal with your backend events, data, and more.

Install

# yarn
yarn add @onesignal/node-onesignal

# npm
npm install @onesignal/node-onesignal --save

Usage

const OneSignal = require('@onesignal/node-onesignal');
import * as OneSignal from '@onesignal/node-onesignal';

Creating a client

Configuration

We can configure the client using the createConfiguration function. You can find more info on each configuration parameter here.

const configuration = OneSignal.createConfiguration(configParams);

Initializing the Client

const client = new OneSignal.DefaultApi(configuration);

Authentication

You can configure auth parameters passing them like this:

const configuration = OneSignal.createConfiguration({
    userAuthKey: '<YOUR_USER_AUTH_KEY>',
    restApiKey: '<YOUR_REST_API_KEY>',
});

const client = new OneSignal.DefaultApi(configuration);

Advanced Usage: Creating a brand-new app

If creating a new app via the client, the response will return the app's API key via the basic_auth_key response parameter. You can then use this to modify your configuration object and create a new client that will have both user-level and app-level authentication set up.

const response = await client.createApp(newapp);

const configuration = OneSignal.createConfiguration({
    userAuthKey: '<YOUR_USER_KEY_TOKEN>',
    restApiKey: response.basic_auth_key,
});

const client = new OneSignal.DefaultApi(configuration);

API Reference

See the full list of API Endpoints.

To make stateful changes requests should take on the following pattern:

  1. create or get an object
  2. make changes to that object
  3. pass the object to the request function to make the changes

Examples of important OneSignal objects include App, Notification, User, and Segment.

For example, see the section below on creating an app. First an app object is created via the instantiation of the App class. Then, the app instance is modified directly. Finally, we use the client to create the app via a remote request.

Creating an app

Creates a new OneSignal app.

Example

const app = new OneSignal.App();

// configure your application
app.name = 'app_name';
app.gcm_key = '<your key here>';
app.android_gcm_sender_id = '<your id here>';

const response = await client.createApp(app);

Getting an app

View the details of a single OneSignal app.

Example

const app = await client.getApp('<app id>');

Getting multiple apps

View apps.

Example

const apps = await client.getApps();

Updating an app

Updates the name or configuration settings of an existing OneSignal app.

Example

const app = new OneSignal.App();
app.name = 'modified_app_name';

const udpateAppResponse = await client.updateApp('<existing_app_id>', app);

Creating a notification

Sends a notification to your users.

Example

const notification = new OneSignal.Notification();
notification.app_id = app.id;
// Name property may be required in some case, for instance when sending an SMS.
notification.name = "test_notification_name";
notification.contents = {
  en: "Gig'em Ags"
}

// required for Huawei
notification.headings = {
  en: "Gig'em Ags"
}
const notification = await client.createNotification(notification);

Creating a notification using Filters

Sends a notification to your users filtered by specific criteria.

Example

const notification = new OneSignal.Notification();
notification.app_id = app.id;

notification.contents = {
  en: "Gig'em Ags"
}

// required for Huawei
notification.headings = {
  en: "Gig'em Ags"
}

// Find all the users that have not spent any amount in USD on IAP.
// https://documentation.onesignal.com/reference/create-notification#send-to-users-based-on-filters
notification.filters = [
    {
        field: 'amount_spent',
        relation: '=',
        value: "0"
    },
];

const notification = await client.createNotification(notification);

Canceling a notification

Stop a scheduled or currently outgoing notification.

Example

const cancelNotificationResponse = await client.cancelNotification('<app id>', '<notification id>');

Getting a notification

View the details of a single notification and outcomes associated with it.

Example

await client.getNotification('<app id>', '<notification id>');

Getting notifications

View the details of multiple notifications.

Param Type Description
app_id string The OneSignal App ID for your app. Available in Keys & IDs.
limit string How many notifications to return. Max is 50. Default is 50.
offset number Page offset. Default is 0. Results are sorted by queued_at in descending order. queued_at is a representation of the time that the notification was queued at.
kind number Kind of notifications returned: * unset - All notification types (default) * 0 - Dashboard only * 1 - API only * 3 - Automated only

Example

const notifications = await client.getNotifications('<app id>', '50', 0, 1);

Getting notification history

View the devices sent a message - OneSignal Paid Plan Required This method will return all devices that were sent the given notification_id of an Email or Push Notification if used within 7 days of the date sent.

Example

const notificationHistory = await client.getNotificationHistory('<notification id>');

Creating a segment

Create segments visible and usable in the dashboard and API - Required: OneSignal Paid Plan

Example

const segment = new OneSignal.Segment();

segment.filters = [
  { field: 'session_count', relation: '&gt;', value: '1' },
  { field: 'tag', key: 'my_tag', relation: 'exists' }
]

const segment = await client.createSegments(app.id, segment);

Deleting a segment

Delete segments (not user devices) - Required: OneSignal Paid Plan You can delete a segment under your app by calling this API. You must provide an API key in the Authorization header that has admin access on the app. The segment_id can be found in the URL of the segment when viewing it in the dashboard.

Example

const deleteSegmentsResponse = await client.deleteSegments('<app id>', '<segment id>');

Creating a player

Add a device.

Example

const player = new OneSignal.Player();
player.device_type = 1;
player.app_id = app_id;
player.identifier = '<identifier>';
const player = await client.createPlayer(player);

Getting a player

View the details of an existing device in one of your OneSignal apps. The email and the hash is only required if you have enabled Identity Verification and device_type is email.

Example

const player = await client.getPlayer('<app id>', '<player id>', '<email auth hash>');

Getting players

View the details of multiple devices in one of your OneSignal apps.

โš ๏ธ Unavailable for Apps Over 80,000 Users.

Param Type Description
app_id string The OneSignal App ID for your app. Available in Keys & IDs.
limit string How many devices to return. Max is 300. Default is 300
offset number Result offset. Default is 0. Results are sorted by id;

Example

const players = await client.getPlayers('<app id>', '300', 0);

Exporting a player

Generate a compressed CSV export of all of your current user data. This method can be used to generate a compressed CSV export of all of your existing user data and is a better alternative to retrieving this data using the /players API endpoint.

See full CSV Export Reference

Example

const exportPlayerResponse = await client.exportPlayer('<app id>', {
  extra_fields: ['location', 'external_user_id'],
  last_active_since: 1469392779,
  segment_name: "Subscribed Users"
});

Updating a player

Update an existing device in one of your OneSignal apps.

Example

const updatePlayerResponse = await client.updatePlayer('<player id>', player);

Updating player tags

Update an existing device's tags in one of your OneSignal apps using the External User ID.

const playerToUpdate = new OneSignal.Player();

player.app_id = APP_ID;
player.device_type = 1;

playerToUpdate.external_user_id = 'your_player_external_id'; // setting the same external_user_id as before
const updatePlayerTagsRequestBody = new OneSignal.UpdatePlayerTagsRequestBody();
updatePlayerTagsRequestBody.tags = {'typescript_test_tag': 1};
const updatePlayerResponse = await api.updatePlayerTags(APP_ID, PLAYER_EXTERNAL_USER_ID, updatePlayerTagsRequestBody);

Deleting Tags

To delete a tag, include its key and set its value to blank (""). Omitting a key/value will not delete it.

For example, if you wanted to delete two existing tags rank and category while simultaneously adding a new tag class, the tags JSON would look like the following:

Example

"tags": {
   "rank": "",
   "category": "",
   "class": "my_new_value"
}

Deleting a player

Deletes a user record.

Example

const deletePlayerResponse = await client.deletePlayer(app.id, '<player id>')

Getting outcomes

View the details of all the outcomes associated with your app.

๐Ÿšง Requires your OneSignal App's REST API Key, available in Keys & IDs ๐Ÿšง

Outcome data are accessible for 30 days before being deleted from our servers. You can export this data monthly if you need it for a more extended period.

Param Type Description
app_id string The OneSignal App ID for your app. Available in Keys & IDs.
outcome_names string Required Comma-separated list of names and the value (sum/count) for the returned outcome data. Note: Clicks only support count aggregation. For out-of-the-box OneSignal outcomes such as click and session duration, please use the โ€œosโ€ prefix with two underscores. For other outcomes, please use the name specified by the user. Example:os__session_duration.count,os__click.count,CustomOutcomeName.sum
outcome_names2 string If outcome names contain any commas, then please specify only one value at a time. Example: outcome_names[]=os__click.count&outcome_names[]=Sales, Purchase.count where โ€œSales, Purchaseโ€ is the custom outcomes with a comma in the name.
outcome_time_range string Optional Time range for the returned data. The values can be 1h (for the last 1 hour data), 1d (for the last 1 day data), or 1mo (for the last 1 month data). Default is 1h if the parameter is omitted.
outcome_platforms string Optional Platform id. Refer device's platform ids for values. Example: outcome_platform=0 for iOS outcome_platform=7, 8 for Safari and Firefox Default is data from all platforms if the parameter is omitted.
outcome_attribution string Optional Attribution type for the outcomes. The values can be direct or influenced or unattributed. Example: outcome_attribution=direct Default is total (returns direct+influenced+unattributed) if the parameter is omitted.

Example

const outcomes = await client.getOutcomes(app.id, 'os__click.count,os_session_duration.count,my_outcome.sum');

Begin Live Activity

Starts a Live Activity event

// Create a player first
const player = new OneSignal.Player();
player.device_type = 0;
player.app_id = '<app id>';
const playerResponse = await api.createPlayer(player);

// Prepare a request
const beginLiveActivityRequest: BeginLiveActivityRequest = {
    push_token: '<push_token>',
    subscription_id: playerResponse.id!,
};
const activityId = '<activity_id>'; // any string

// Begin activity
await api.beginLiveActivity('<app_id>', activityId, beginLiveActivityRequest);

Update Live Activity

Updates a Live Activity event

const updateLiveActivityRequest: UpdateLiveActivityRequest = {
    event_updates: {
        data: 'test'
    },
    event: "update",
    name: "contents"
};

await api.updateLiveActivity('<app_id>', '<activity_id>', updateLiveActivityRequest);

End Live Activity

Stops a Live Activity event

const subscriptionId = '<subscription_id>'; // player id
await api.endLiveActivity('<app_id>', '<activity_id>', subscriptionId);

Subscription types

  • iOSPush
  • AndroidPush
  • FireOSPush
  • ChromeExtensionPush
  • ChromePush
  • WindowsPush
  • SafariLegacyPush
  • FirefoxPush
  • macOSPush
  • HuaweiPush
  • SafariPush
  • Email
  • SMS

Users

Creating a OneSignal User

const user = new OneSignal.User();

const aliasLabel = '<alias_label>';
const aliasId = '<alias_id>';
const subscriptionToken = '<subscription_token>';

user.identity = {
    [aliasLabel]: aliasId,
};

user.subscriptions = [
  {
    type: "iOSPush",
    token: subscriptionToken,
  }
];

const createdUser = await api.createUser('<app_id>', user);
assert(createdUser.identity!['onesignal_id'] != null);

Getting a user by onesignal_id

const oneisgnalAliasLabel = "onesignal_id";
const onesignalAliasId = createdUser.identity!['onesignal_id'];

const fetchedUser = await api.fetchUser('<app_id>', oneisgnalAliasLabel, onesignalAliasId);

Getting a user by an alias

const fetchedUser = await api.fetchUser('<app_id>', alias_label, alias_id);

Updating a user

const updateUserRequest: UpdateUserRequest = {
    properties: {
        language: 'fr'
    }
};

const updatedUser = await api.updateUser('<app_id>', aliasLabel, aliasId, updateUserRequest);

Deleting a user

await api.deleteUser('<app_id>', aliasLabel, aliasId);

Subscriptions

Creating a subscription for existing user

const createSubscriptionRequestBody: CreateSubscriptionRequestBody = {
    subscription: {
        type: "AndroidPush",
        token: '<subscription_token>',
    }
};

const response = await api.createSubscription('<app_id>', '<alias_label>', '<alias_id>', createSubscriptionRequestBody);

Updating a subscription

const updateSubscriptionRequestBody: UpdateSubscriptionRequestBody = {
    subscription: {
        type: "iOSPush",
        token: '<new-subscription-token>',
    }
};

await api.updateSubscription('<app_id>', '<existing_subscription_id>', updateSubscriptionRequestBody);

Deleting a subscription

await api.deleteSubscription('<app_id>', '<subscription_id>');

Transfer subscription ownership

Transfers the subscription from one user to another.

// Setting the user for transfering the subscription to. User is identyfied by an IdentityObject.
const transferSubscriptionRequestBody: TransferSubscriptionRequestBody = {
    identity: otherUserIdentityObject
};

const transferResponse = await api.transferSubscription('<app_id>', '<subscription_id>', transferSubscriptionRequestBody);

Aliases

Fetching aliases for a user

const fetchResponse = await api.fetchAliases('<app_id>', '<subscription_id>');

Fetching user identity

const fetchResponse = await api.fetchUserIdentity('<app_id>', '<alias_label>', '<alias_id>');

Identifying user by alias

const userIdentityRequestBody: UserIdentityRequestBody = {
    identity: {
        ['<new_alias_label>']: '<new_alias_id>'
    }
};

const identifyResponse = await api.identifyUserByAlias('<app_id>', 
                                                       '<existing_alias_label>', 
                                                       '<existing_alias_id>',
                                                       userIdentityRequestBody);

Identifying user by subscription id

const userIdentityRequestBody: UserIdentityRequestBody = {
    identity: {
        ['<new_alias_label>']: '<new_alias_id>'
    }
};

const identifyResponse = await api.identifyUserBySubscriptionId('<app_id>', '<existing_subscription_id>', userIdentityRequestBody);

Deleting an alias

await api.deleteAlias('<app_id>', '<alias_label>', '<alias_id>', '<alias_label_to_delete>');

Author

๐Ÿค Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page.

Show your support

Give a โญ๏ธ if this project helped you!

๐Ÿ“ License

Copyright ยฉ 2023 OneSignal.

This project is MIT licensed.

onesignal-node-api's People

Contributors

emawby avatar jkasten2 avatar jmadler avatar kesheshyan avatar nan-li avatar rgomezp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

onesignal-node-api's Issues

[Bug]: Does not support ios_interruption_level

What happened?

Title says it all.

Steps to reproduce?

1. Try to send ios_interruption_level in the api request
2. It wont be sent to onesignal with this API.

What did you expect to happen?

ios_interruption_level should be acknowledged by this api.

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Operators not supported in notification filters

What happened?

When trying to add filters to a notification but not only with Filter instances but also with Operator instances, the serialization process first turns all values of the Operator into undefined and the resulting payload will then carry an emtpy object {}.

[
    {
        "field": "tag",
        "key": "value",
        "relation": "=",
        "value": "value"
    },
    {
        "field": undefined,
        "key": undefined,
        "relation": undefined,
        "value": undefined
    },
    {
        "field": "tag",
        "key": "value",
        "relation": "=",
        "value": "value"
    }
]

The issues seems to be that internally the filter property of a Notification is set to be of type Array<Filter>. The ObjectSerializer therefore ignores the operator: "OR" as it's not a field of Filter. As a result, the request fails because of a BadRequest error with Body: {"errors":["Segment is not a valid filter field."]}.

The serialization happens here

} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.serialize(date, subType, format));
}
return transformedData;
. Either the filter property would not only be Array<Filter> (see
'filters'?: Array<Filter>;
) but instead Array<Filter|Operator> and that would properly be parsed. Or you just allow objects to be passed without serializing them through the ObjectSerializer.

In the Go SDK, this case seems to be handled as expected: https://github.com/OneSignal/onesignal-go-api/blob/a573325af1d37a1c7dc8bad8d78fdd33fbfcaf38/model_filter_expressions.go#L27-L54

Also the NodeJS SDK docs state that it should be possible to pass { operator: "OR"}.

Steps to reproduce?

1. create a new notification
2. set `filter` to an array of [Filter, Operator, Filter] instances
3. send the notification

What did you expect to happen?

The notification should be sent and the filter fields in the OneSignal dashboard should show that the notification was sent with three filters, the second being the "OR" operator.

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: createNotification does not work

What happened?

  • createNotification does not work.
  • I guess the reason of error is as follows:

Steps to reproduce?

1. install 1.0.0beta9
2. setting configuration
3. run createNotification
4. not working

What did you expect to happen?

works normally, and sent push message

Relevant log output

{"errors":["Please include a case-sensitive header of Authorization: Basic <YOUR-REST-API-KEY-HERE> or Bearer token=\"<YOUR-REST-API-KEY-HERE>\" with a valid REST API key."]}
Headers: {"access-control-allow-headers":"SDK-Version","access-control-allow-origin":"*","alt-svc":"h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400","cache-control":"no-cache","cf-cache-status":"DYNAMIC","cf-ray":"78c4f54cec66a7e3-ICN","connection":"close","content-type":"application/json; charset=utf-8","date":"Fri, 20 Jan 2023 04:10:03 GMT","referrer-policy":"strict-origin-when-cross-origin","server":"cloudflare","status":"400 Bad Request","strict-transport-security":"max-age=15552000; includeSubDomains","transfer-encoding":"chunked","vary":"Origin","via":"1.1 google","x-content-type-options":"nosniff","x-download-options":"noopen","x-frame-options":"SAMEORIGIN","x-permitted-cross-domain-policies":"none","x-request-id":"b0fc6853-25f3-4ea5-92f7-2ecd96f711eb","x-runtime":"0.005988","x-xss-protection":"1; mode=block"}
    at new ApiException (/Users/yohaanyoon/classting/classting-push-service/node_modules/@onesignal/node-onesignal/dist/apis/exception.js:22:28)
    at DefaultApiResponseProcessor.<anonymous> (/Users/yohaanyoon/classting/classting-push-service/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:1707:31)
    at step (/Users/yohaanyoon/classting/classting-push-service/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:48:23)
    at Object.next (/Users/yohaanyoon/classting/classting-push-service/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:29:53)
    at fulfilled (/Users/yohaanyoon/classting/classting-push-service/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:20:58)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 400,
  body: BadRequestError {
    errors: [
      'Please include a case-sensitive header of Authorization: Basic <YOUR-REST-API-KEY-HERE> or Bearer token="<YOUR-REST-API-KEY-HERE>" with a valid REST API key.'
    ]
  },
  headers: {
    'access-control-allow-headers': 'SDK-Version',
    'access-control-allow-origin': '*',
    'alt-svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400',
    'cache-control': 'no-cache',
    'cf-cache-status': 'DYNAMIC',
    'cf-ray': '78c4f54cec66a7e3-ICN',
    connection: 'close',
    'content-type': 'application/json; charset=utf-8',
    date: 'Fri, 20 Jan 2023 04:10:03 GMT',
    'referrer-policy': 'strict-origin-when-cross-origin',
    server: 'cloudflare',
    status: '400 Bad Request',
    'strict-transport-security': 'max-age=15552000; includeSubDomains',
    'transfer-encoding': 'chunked',
    vary: 'Origin',
    via: '1.1 google',
    'x-content-type-options': 'nosniff',
    'x-download-options': 'noopen',
    'x-frame-options': 'SAMEORIGIN',
    'x-permitted-cross-domain-policies': 'none',
    'x-request-id': 'b0fc6853-25f3-4ea5-92f7-2ecd96f711eb',
    'x-runtime': '0.005988',
    'x-xss-protection': '1; mode=block'
  }
}

Code of Conduct

  • I agree to follow this project's Code of Conduct

require won't find the module

Hi,
I'm trying to use this module with firebase functions (using require) and I get this error:

Cannot find module [__edited__]/monorepo/node_modules/@onesignal/node-onesignal/dist/index.js'. Please verify that the package.json has a valid "main" entry

I believe is because you added dist in .gitignore?

Thank you.

[question]: How to pass name to Notification

How can we help?

I'm using Notification model and i'm trying to send a SMS notification but i can't set name property of notification, required for sms notification. Is that a bug? Or i'm missing something?

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: createNofitication returning { id: '', errors: {} }

What happened?

I have some cases of sending push notifications where I cannot identify the errors and the createNotification function does not return any information about the error.

Steps to reproduce?

version 2.0.1-beta2

I create the object with the OneSignalNotification type

and send with await this.oneSignalService.createNotification(notificationsBody);

when sent successfully it returns the right information but there is no error, I am just receiving errors: {}

What did you expect to happen?

I hope that at least I can get back to the error that happened

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Unable to create a notification in Supabase Deno runtime

What happened?

When I run this line of code in a Deno environment,const res = await onesignal.createNotification(notification), I get the following error: TypeError: (0 , Pa.default) is not a function.

I tried running the same sample in a Node environment; it worked fine.

For reference, here's my code:

const OnesignalAppId = process.env["ONESINGAL_APP_ID"]!;
const configuration = OneSignal.createConfiguration({
  userKey: process.env["ONESINGAL_USER_KEY"]!,
  appKey: process.env["ONESINGAL_APP_KEY"]!,
});
const osClient = new OneSignal.DefaultApi(configuration);
export const sendNotif = async (message: string, segments: string[]) => {
  console.log("App ID", OnesignalAppId);
  try {
    const notification = new OneSignal.Notification();
    notification.app_id = OnesignalAppId;
    notification.contents = {
      en: message,
    };
    notification.included_segments = [...segments];

    const res = await osClient.createNotification(notification);
    console.info("CreateNotif Response", res);
  } catch (err) {
    console.error(err);
  }
};

Steps to reproduce?

1. Create a supabase edge function
2. Implement a function to send a notification
3. Request the edge function 
4. Observe that no motivation is received and an error message is produced.

What did you expect to happen?

I expected it to work and send my device a notification.

Relevant log output

TypeError: (0 , Pa.default) is not a function
    at t.send (https://esm.sh/v113/@onesignal/[email protected]/deno/node-onesignal.mjs:2:1725)
    at https://esm.sh/v113/@onesignal/[email protected]/deno/node-onesignal.mjs:5:95902
    at https://esm.sh/v113/@onesignal/[email protected]/deno/node-onesignal.mjs:2:1392
    at async Server.<anonymous> (file:///home/deno/functions/push-to-all-subs/index.ts:20:17)
    at async Server.#respond (https://deno.land/[email protected]/http/server.ts:299:18)

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: How does one fetch the "optedIn" status for a user?

How can we help?

The mobile app SDK has two methods: OptIn and OptOut to specify whether the user is opted in to receive push notifications or not. There is also a optedIn method to find out what the value is.

How do I fetch that value with onesignal-node-api ?

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Missing support for critical email features

What's on your mind?

[Bug]: Missing support for critical email features

Missing support for the following API parameters:

Generic:

  • custom_data

Mail type specific:

  • include_unsubscribed
  • disable_email_click_tracking

Lack of these features makes this SDK unusable for any kind of transactional email setup containing sensitive data such as password reset tokens. Setting these to the notification object results in the SDK stripping them away and eventually not sending them to the API.

Only solution is to resort to using fetch or similar tools to fetch data and completely lose type safety.

In my opinion this is a high priority issue that should be addressed, but I won't wait for an update nor contribute to the code: if I had the time to do so I would not be looking to use a third-party for my email and notifications needs. I expect paid software SDKs to work, especially for mature companies such as OneSignal. Guess I'm wrong, wasted my time, and I'll be looking elsewhere.

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: Notification email preheader attribute

How can we help?

Hello!

This might be a bug, but I can't figure out how to include email preheaders in notifications I create. I don't see it in the Notifications model - is this just not yet implemented?

For context, I'm using 1.0.0-beta8.

Thank you :)

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Executing `getPlayer` request with Identity Verification enabled is throwing an error

What happened?

I am using the node client to interact with OneSignal's API and I am having trouble getting players since I enabled Identity Verification. I followed this and this documentation page but I always get a 400 response.

Steps to reproduce?

Just run this snippet with valid values, in my case I am trying to get a player which has the device type equal to 11 (email):

const OneSignal = require("@onesignal/node-onesignal");
const crypto = require("crypto");

const APP_ID = "*******************************";

const app_key_provider = {
  getToken() {
    return "*****************************8";
  },
};

// configuration object
let configuration = OneSignal.createConfiguration({
  authMethods: {
    app_key: {
      tokenProvider: app_key_provider,
    },
  },
});

client = new OneSignal.DefaultApi(configuration);


const getPlayer = async (playerId, email) => {
  if (email) {
    const hmac = crypto.createHmac("sha256", app_key_provider.getToken());
    hmac.update(email);

    return await client.getPlayer(APP_ID, playerId, hmac.digest("hex"));
  }
  return await client.getPlayer(APP_ID, playerId);
};

(async function () {
await getPlayer(
    "someplayerid",
    "[email protected]"
  );
})();

What did you expect to happen?

I expected to receive the requested player. I am able to retrieve players without device type=email and I was printing some values inside the client code and it has the email auth hash available and builds the request with it. I am assuming it's something in the API itself and not the client.

Relevant log output

Error: HTTP-Code: 400
Message: "Unknown API Status Code!\nBody: \"[object Object]\""
    at new ApiException (/home/dev/hubspot-private-test/node_modules/@onesignal/node-onesignal/dist/apis/exception.js:20:28)
    at DefaultApiResponseProcessor.<anonymous> (/home/dev/hubspot-private-test/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:1193:31)
    at step (/home/dev/hubspot-private-test/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:46:23)
    at Object.next (/home/dev/hubspot-private-test/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:27:53)
    at /home/dev/hubspot-private-test/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:21:71
    at new Promise (<anonymous>)
    at __awaiter (/home/dev/hubspot-private-test/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:17:12)
    at DefaultApiResponseProcessor.getPlayer (/home/dev/hubspot-private-test/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:1170:16)
    at /home/dev/hubspot-private-test/node_modules/@onesignal/node-onesignal/dist/types/ObservableAPI.js:370:113
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 400,
  body: 'Unknown API Status Code!\nBody: "[object Object]"'
}

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: createConfiguration implementation

How can we help?

This configuration is not correct:

const configuration = OneSignal.createConfiguration({
    userKey: '<YOUR_USER_KEY_TOKEN>',
    appKey: '<YOUR_APP_KEY_TOKEN>',
});

This is what's working:

    const configuration = OneSignal.createConfiguration({
        authMethods: {
            app_key: {
                tokenProvider: {
                    getToken() {
                        return appKey;
                    },
                }
            } as OneSignal.HttpBearerConfiguration,
            user_key: {
                tokenProvider: {
                    getToken() {
                        return userKey;
                    },
                }
            } as OneSignal.HttpBearerConfiguration,
        }
    });

Where can I find userKey and appKey?

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: createNotification returns HTTP-Code: 400 Message: Bad Request Body: {"errors":[{}]}

What happened?

I'm trying to implement a function that we can use to send notifications using OneSignal.
The error I'm getting makes no sense to me.

Steps to reproduce?

static async createNotification(title: string, message: string, userEmail: string, languageCode: string = 'en') {
    const notification = new OneSignal.Notification();

    notification.name = 'Admin notification';
    notification.contents = {
      [languageCode]: message,
    };
    notification.headings = {
      [languageCode]: title,
    };
    notification.filters = [
      {
        field: 'tag',
        key: 'email', // we agreed to use email for the tags
        relation: '=',
        value: userEmail,
      },
    ];

    try {
      return await client.createNotification(notification);
    } catch (error: any) {
      console.error(error.message);
    }

    return 'ERROR';
  }

What did you expect to happen?

Either create the notification, or give me an error message that makes sense.

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: Having problems making a simple fetchUser API call + broken links in docs

How can we help?

I cannot seem to make a simple fetchUser API call work. The documentation tells me to do it like so:

const configuration = OneSignal.createConfiguration({
  userKey: process.env.ONESIGNAL_USER_KEY
  appKey: process.env.ONESIGNAL_APP_ID,
})

const client = new OneSignal.DefaultApi(configuration)

client
  .fetchUser('my_app_id', 'external_id', 'foo')
  .then((data) => {
    logger.debug(data, 'API called successfully. Returned data')
  })
  .catch((error) => logger.error(error, 'Error calling OneSignal'))

It is not totally clear what the userKey and appKey should be so I have assumed that this is the application key and REST API key from the "Keys & IDs" page on the OneSignal Dashboard.

However, when I try that I just get

Error: HTTP-Code: 404
    Message: Unknown API Status Code!
    Body: {}

I saw other issues logged where people have set the configuration like this:

const appKeyProvider = {
  getToken() {
    return process.env.ONESIGNAL_REST_API_KEY as string
  },
}
const configuration = OneSignal.createConfiguration({
  authMethods: {
    app_key: {
      tokenProvider: appKeyProvider,
    },
  },
})

But that just gives me the same error.

I then found this:
https://github.com/OneSignal/onesignal-node-api/blob/main/DefaultApi.md#fetchUser

But that does not work because fetchUser expects 3 (or 4) parameter, not 1.

What am I doing wrong?

As an aside, this https://github.com/OneSignal/onesignal-node-api has broken or misleading links.

The link here does not take you to anywhere useful
image

And this link is broken
image

Code of Conduct

  • I agree to follow this project's Code of Conduct

How to set title and subtitle? (APNS)

How can we help?

Hi,

I'm able to send notifications to iOS using this:
const configurationOnesignal = OneSignal.createConfiguration({
appKey: apiKey,
});

const client = new OneSignal.DefaultApi(configurationOnesignal);

const notification = new OneSignal.Notification();

notification.contents = {
en: "message"
}

What I'd really like to do is replicate what can be done via the one signal website.. set a title, a subtitle and a message.

Is that possible? I've looked through all the docs and even the code so I'm thinking not..

Thanks in advance!

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: CAn't create notification using include_subscription_ids

What happened?

Sending notification using "included_segments" works, however swapping this to use "include_subscription_ids" fails with a 400 error with no meaningful error message


const app_key_provider = {
    getToken() {
        return process.env.ONESIGNAL_APP_KEY;
    }
};
const configuration = OneSignal.createConfiguration({
    authMethods: {
        app_key: {
            tokenProvider: app_key_provider
        }
    }
});

const client = new OneSignal.DefaultApi(configuration);

    const notification = new OneSignal.Notification();

    notification.app_id = ONESIGNAL_APP_ID;
    //notification.included_segments = ['XXXXXXX'];
    notification.include_player_ids = ['XXX-XXX-XXX-XXX'];
    notification.contents = {
        en: "Hello OneSignal!"
    };
    notification.headings = {
        en: "Title"
    };
    
    const oneSignalInfo = await client.createNotification(notification);

Steps to reproduce?

Run the above code with included_segments enabled - works
Run the above code with include_player_ids - fails

Have also tried swapping 'include_player_ids' with 'include_subscription_ids' but same error.

What did you expect to happen?

Notification sent

Relevant log output

{"errorType":"Error","errorMessage":"HTTP-Code: 400\nMessage: Bad Request\nBody: {\"errors\":[{}]}\nHeaders: {\"access-control-allow-headers\":\"SDK-Version\",\"access-control-allow-origin\":\"*\",\"alt-svc\":\"h3=\\\":443\\\"; ma=86400\",\"cache-control\":\"no-cache\",\"cf-cache-status\":\"DYNAMIC\",\"cf-ray\":\"7f93f5078fe934d7-DUB\",\"connection\":\"close\",\"content-type\":\"application/json; charset=utf-8\",\"date\":\"Sat, 19 Aug 2023 17:01:12 GMT\",\"referrer-policy\":\"strict-origin-when-cross-origin\",\"server\":\"cloudflare\",\"set-cookie\":\"__cf_bm=X; path=/; expires=Sat, 19-Aug-23 17:31:12 GMT; domain=.onesignal.com; HttpOnly; Secure; SameSite=None\",\"strict-transport-security\":\"max-age=15552000; includeSubDomains\",\"transfer-encoding\":\"chunked\",\"vary\":\"Origin\",\"via\":\"1.1 google\",\"x-content-type-options\":\"nosniff\",\"x-download-options\":\"noopen\",\"x-frame-options\":\"SAMEORIGIN\",\"x-permitted-cross-domain-policies\":\"none\",\"x-request-id\":\"8d36b0e2-49f1-42d7-8891-a1d4812afe9d\",\"x-runtime\":\"0.009648\",\"x-xss-protection\":\"1; mode=block\"}","code":400,"body":{"errors":[{}]},"headers":{"access-control-allow-headers":"SDK-Version","access-control-allow-origin":"*","alt-svc":"h3=\":443\"; ma=86400","cache-control":"no-cache","cf-cache-status":"DYNAMIC","cf-ray":"7f93f5078fe934d7-DUB","connection":"close","content-type":"application/json; charset=utf-8","date":"Sat, 19 Aug 2023 17:01:12 GMT","referrer-policy":"strict-origin-when-cross-origin","server":"cloudflare","set-cookie":"X=; path=/; expires=Sat, 19-Aug-23 17:31:12 GMT; domain=.onesignal.com; HttpOnly; Secure; SameSite=None","strict-transport-security":"max-age=15552000; includeSubDomains","transfer-encoding":"chunked","vary":"Origin","via":"1.1 google","x-content-type-options":"nosniff","x-download-options":"noopen","x-frame-options":"SAMEORIGIN","x-permitted-cross-domain-policies":"none","x-request-id":"8d36b0e2-49f1-42d7-8891-a1d4812afe9d","x-runtime":"0.009648","x-xss-protection":"1; mode=block"},"stack":["Error: HTTP-Code: 400","Message: Bad Request","Body: {\"errors\":[{}]}","Headers: {\"access-control-allow-headers\":\"SDK-Version\",\"access-control-allow-origin\":\"*\",\"alt-svc\":\"h3=\\\":443\\\"; ma=86400\",\"cache-control\":\"no-cache\",\"cf-cache-status\":\"DYNAMIC\",\"cf-ray\":\"7f93f5078fe934d7-DUB\",\"connection\":\"close\",\"content-type\":\"application/json; charset=utf-8\",\"date\":\"Sat, 19 Aug 2023 17:01:12 GMT\",\"referrer-policy\":\"strict-origin-when-cross-origin\",\"server\":\"cloudflare\",\"set-cookie\":\"X; path=/; expires=Sat, 19-Aug-23 17:31:12 GMT; domain=.onesignal.com; HttpOnly; Secure; SameSite=None\",\"strict-transport-security\":\"max-age=15552000; includeSubDomains\",\"transfer-encoding\":\"chunked\",\"vary\":\"Origin\",\"via\":\"1.1 google\",\"x-content-type-options\":\"nosniff\",\"x-download-options\":\"noopen\",\"x-frame-options\":\"SAMEORIGIN\",\"x-permitted-cross-domain-policies\":\"none\",\"x-request-id\":\"8d36b0e2-49f1-42d7-8891-a1d4812afe9d\",\"x-runtime\":\"0.009648\",\"x-xss-protection\":\"1; mode=block\"}"," at new ApiException (/var/task/node_modules/@onesignal/node-onesignal/dist/apis/exception.js:22:28)"," at DefaultApiResponseProcessor.<anonymous> (/var/task/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:1770:31)"," at step (/var/task/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:48:23)"," at Object.next (/var/task/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:29:53)"," at fulfilled (/var/task/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:20:58)"," at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"]}

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: What's the simplest way to create a notification using a custom icon?

How can we help?

Notifications created using this client have the OneSignal notification bell as the default icon. It seems possible to specify a custom icon, but it's unclear if people need to set every *icon property.

The types have 10 properties to set.

https://github.com/OneSignal/node-onesignal/blob/3b399a35a7b625295ea3f46088b7a7af7f65dbce/models/Notification.ts#L260-L299

Is there a way to specify the icon once?

Code of Conduct

  • I agree to follow this project's Code of Conduct

Error on Create Notification

Hello! I am getting the following error when trying to create a notification.

Here is the code I am running

const OneSignal = require("@onesignal/node-onesignal");

  let configuration = OneSignal.createConfiguration({
    authMethods: {
      user_key: {
        tokenProvider: user_key_provider,
      },
      app_key: {
        tokenProvider: app_key_provider,
      },
    },
  });

  const OneSignalclient = await new OneSignal.DefaultApi(configuration);

  const OneSignalApp = await OneSignalclient.getApp(MY_APP_ID);
  const notification = new OneSignal.Notification();
  notification.app_id = OneSignalApp.id;
  notification.contents = {
    en: "contents is here",
  };
  notification.headings = {
    en: "heading is here",
  };
  notification.include_external_user_ids = ["2"];

  await OneSignalclient.createNotification(notification, {
    Authorization: MY_API_KEY});

Here is the error:

TypeError: Cannot read properties of undefined (reading 'makeRequestContext') at DefaultApiRequestFactory.<anonymous> (/home/elizabeth/Programming/Websites/debacle/server/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:137:61) at step (/home/elizabeth/Programming/Websites/debacle/server/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:46:23) at Object.next (/home/elizabeth/Programming/Websites/debacle/server/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:27:53) at /home/elizabeth/Programming/Websites/debacle/server/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:21:71 at new Promise (<anonymous>) at __awaiter (/home/elizabeth/Programming/Websites/debacle/server/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:17:12) at DefaultApiRequestFactory.createNotification (/home/elizabeth/Programming/Websites/debacle/server/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:127:16) at ObservableDefaultApi.createNotification (/home/elizabeth/Programming/Websites/debacle/server/node_modules/@onesignal/node-onesignal/dist/types/ObservableAPI.js:63:57) at PromiseDefaultApi.createNotification (/home/elizabeth/Programming/Websites/debacle/server/node_modules/@onesignal/node-onesignal/dist/types/PromiseAPI.js:18:31) at main (/home/elizabeth/Programming/Websites/debacle/server/dist/index.js:166:27)

[Bug]: Can't create notifications targeting a list of external ids

What happened?

The REST API makes it possible to send notifications to a list of users given their external ids: https://documentation.onesignal.com/reference/create-notification#platform-to-deliver-to

However the sdk doesn't seem to make it possible, because the field include_aliases expects an object of type PlayerNotificationTargetIncludeAliases, which definition doesn't make it possible to define the external_id field.

This is what the serialized JSON for include_aliases should look like according to REST API documentation

  "include_aliases": {
    "external_id": ["external_user_id_on_push_email_sms"]
  },

Steps to reproduce?

Install latest version of sdk.

To try and make the call with the SDK, run:

    const notification = new OneSignal.Notification()
    notification.app_id = this.appId
    notification.include_aliases = new OneSignal.PlayerNotificationTargetIncludeAliases();
    notification.include_aliases.external_id = ["my-id-1", "my-id-2"]

Typescript will complain that

"Property 'external_id' does not exist on type 'PlayerNotificationTargetIncludeAliases'.ts(2339)"

What did you expect to happen?

I expect the SDK to have the correct type definition of PlayerNotificationTargetIncludeAliases so that the API call can be made with the correct parameters.

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Missing app_id in Player object causes update failures

What happened?

Recently, it was observed that players returned by the onesignal-node-api library do not contain the app_id property, which was previously included. This absence causes issues, particularly when attempting to update player information, as the operation expects a valid app_id, resulting in errors.

Steps to reproduce?

To reproduce the issue, simply retrieve a player using the library and attempt to update the player's information without manually adding an app_id. The library will throw an error indicating that app_id must be a valid UUID.

What did you expect to happen?

I expected the player object retrieved from the library to include the app_id property automatically, allowing for seamless updates without the need for manual intervention.

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Having issue with external ids for specific user targeted notification

What happened?

I'm using node Js to trigger notifications using external Ids even though the notifications are getting triggered for all users.
I'm facing issues when triggering device specific notification

  1. external_id is showing up as "null".
  2. the error statement even after using "notification.include_aliases = { "external_id": externalIds }"
CreateNotificationSuccessResponse {
  id: 'ae3093eb-3bda-41a3-b67d-b0281991a08b',
  external_id: null,
  errors: { invalid_aliases: { external_id: [Array] } }
}

Steps to reproduce?

Node version : v21.4.0
One signal version : "@onesignal/node-onesignal": "^5.0.0-alpha-01",

1. Created node js function to trigger notification


const OneSignal = require('@onesignal/node-onesignal');
const { ONE_SIGNAL_CONFIG } = require('../config/app.config');

const configuration = OneSignal.createConfiguration({
    userAuthKey: ONE_SIGNAL_CONFIG.AUTH_KEY,
    restApiKey: ONE_SIGNAL_CONFIG.API_KEY,
});

const client = new OneSignal.DefaultApi(configuration);

// Function to send mobile notifications
async function sendNotification(externalIds, message) {
    try {
 
        //createNotification
        const notification = new OneSignal.Notification();
        notification.app_id = ONE_SIGNAL_CONFIG.APP_ID;
        notification.name = "external_id";
        notification.contents = {
            en: message
        }

        // required for Huawei
        notification.headings = {
            en: "External Id"
        }
        // Note: Tried passing static external id for testing
        notification.external_id = '66378fb25e9d1a7f26c5252b'
        
        //Note: passed array of externalIds. For e.g (['66378fb25e9d1a7f26c5252b']
        notification.include_aliases = { "external_id": externalIds }
        notification.target_channel = "push"
        const notificationResponse = await client.createNotification(notification);

        console.log('Notification sent:', notificationResponse);
        return notificationResponse;
    } catch (error) {
        console.error('Error sending notification:', error);
        throw error;
    }
}

module.exports = { sendNotification };



2. Called the function in one of my API

// Send notification
sendNotification([profile._id], 'PROFILE NOTIFICATION')
  .then(() => console.log('Notification sent successfully'))
  .catch(error => console.error('Error sending notification:', error));

3. Called following functions in initState() of my flutter project


  Future<void> initPlatform() async {
    OneSignal.Debug.setLogLevel(OSLogLevel.verbose);

    OneSignal.Debug.setAlertLevel(OSLogLevel.none);
    OneSignal.initialize(AppKeys.oneSignalAppId);
    OneSignal.Notifications.requestPermission(true);

    print(
        'ONE_SIGNAL IDs... ${await OneSignal.User.getOnesignalId()}'); 
    print(
        'ONE_SIGNAL IDs.... External... ${await OneSignal.User.getExternalId()}'); 
  }


  loginOneSignal() async {
    final externalId = await OneSignal.User.getExternalId();
    if (externalId == null) {
      final userId = ref.watch(accountPageProvider).profile?.sId;
      if (userId != null) {
        await OneSignal.logout();
        await OneSignal.login(userId);
      }
    }
  }

What did you expect to happen?

I expected that the notifications will be shown only in the target devices which have logged into oneSignal with custom Id.
For e.g. OneSignal.login('custom_id')

Relevant log output

CreateNotificationSuccessResponse {
  id: 'ae3093eb-3bda-41a3-b67d-b0281991a08b',
  external_id: null,
  errors: { invalid_aliases: { external_id: [Array] } }
}

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Feature Request]: mix this.configuration and _options in api method

What's on your mind?

Mix this.configuration and _options instead of _config || this.configuration can make api easier for use.

For example I have a system which manage lots of apps, and I set userKey in the createConfiguration to manage apps. When I want to send notifications to one app, I can set the apiKey in the _options parameter, but I also need to provide parameters like baseServer, httpApi and middleware. Mix this.configuration and _options can make properties of the _options parameter optional.

Create a new DefaultApi instance every time is a way to solve this problem, but sometimes I want to make sure that only one instance exists, like using with NestJS.

Code of Conduct

  • I agree to follow this project's Code of Conduct

Node :REST API create notification returns 403 Forbidden error with Cloudflare Recaptcha html

Description:

This is the link to my sample code repo
https://github.com/MuhammadUmarZahid/one-signal-node

I am trying to send OneSignal notifications from the node project using REST API provided by OneSignal.
Everything seemed to be working till yesterday. All of sudden today the endpoint:

/api/v1/notifications

started returning in response:

{
status: 403,
statusText: 'Forbidden',
data: ...
.....
}

The data key in the response had cloudflare html page which shows recaptcha. I dont know how should i solve the recaptcha on the server without opening a browser.

The same error started popping in my Android app registered against the same app id on the onesignal dashboard.

Please help me with this as i want to go into production asap,

Environment

node version 16.4.0
npm version 7.18.1
Visual Studio Code 1.64.1
Axios 0.25.0

Steps to Reproduce Issue:

  1. Unknown but maybe i sent more requests to the onesignal server in the past 2 to 3 days which caused the cloudflare ddos protection to trigger.

Anything else:

see above

[Bug]: Can't find type declaration.

What happened?

I'm getting this error after using import * as OneSignal from '@onesignal/node-onesignal';:

Cannot find module '@onesignal/node-onesignal' or its corresponding type declarations.

Steps to reproduce?

1. Install `@onesignal/node-onesignal`.
2. Importing library: `import * as OneSignal from '@onesignal/node-onesignal';`

What did you expect to happen?

I expected normal behavior.

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: 1.0.0-beta5 package broken

What happened?

The latest NPM package doesn't contain the 'dist' folder, so the module can't be included.

Steps to reproduce?

Install 1.0.0-beta5 into project and try to run.

What did you expect to happen?

To work.

Have had to fix my dependency to 1.0.0-beta4 for my project to build and run.

Relevant log output

Nov 15 16:45:51 ip-xxx-xxx-xxx web: Error: Cannot find module '/var/app/current/dist/apps/api-team/node_modules/@onesignal/node-onesignal/dist/index.js'
Nov 15 16:45:51 ip-xxx-xxx-xxx web: at createEsmNotFoundErr (node:internal/modules/cjs/loader:1012:15)
Nov 15 16:45:51 ip-xxx-xxx-xxx web: at finalizeEsmResolution (node:internal/modules/cjs/loader:1005:15)
Nov 15 16:45:51 ip-xxx-xxx-xxx web: at resolveExports (node:internal/modules/cjs/loader:522:14)
Nov 15 16:45:51 ip-xxx-xxx-xxx web: at Function.Module._findPath (node:internal/modules/cjs/loader:562:31)
Nov 15 16:45:51 ip-xxx-xxx-xxx web: at Function.Module._resolveFilename (node:internal/modules/cjs/loader:971:27)
Nov 15 16:45:51 ip-xxx-xxx-xxx web: at Function.Module._load (node:internal/modules/cjs/loader:833:27)
Nov 15 16:45:51 ip-xxx-xxx-xxx web: at Module.require (node:internal/modules/cjs/loader:1057:19)
Nov 15 16:45:51 ip-xxx-xxx-xxx web: at require (node:internal/modules/cjs/helpers:103:18)
Nov 15 16:45:51 ip-xxx-xxx-xxx web: at Object.4124 (/var/app/current/dist/apps/api-team/main.js:57:952744)
Nov 15 16:45:51 ip-xxx-xxx-xxx web: at __webpack_require__ (/var/app/current/dist/apps/api-team/main.js:57:972415) {
Nov 15 16:45:51 ip-xxx-xxx-xxx web: code: 'MODULE_NOT_FOUND',
Nov 15 16:45:51 ip-xxx-xxx-xxx web: path: '/var/app/current/dist/apps/api-team/node_modules/@onesignal/node-onesignal/package.json'
Nov 15 16:45:51 ip-xxx-xxx-xxx web: }

Code of Conduct

  • I agree to follow this project's Code of Conduct

Can I NOT await for onesignal result?

How can we help?

I am using the "client.createNotification(notification)" function in my node JS API.

Since I actually don't care about the returned info from this promise, can I just call it without await and keep doing my API stuff and return the rest that doesn't rely at all on the result of this onesignal resolution?

Basically I only want to trigger the notification sending from onesignal and ignore the rest.

WHY? Because sometimes Onesignal has response time issue for whatever reason (crash / maintenance / whatever), or even throws unknown error etc; all the above crashing my heroku dynos / job, or making my API super slow since all my dynos may be either crashed by onesignal issue or pending for their response time.

Thank you for your help!

Extra information if that helps:

Here are some of the errors that constantly crash the associated heroku dynos and seems to happen randomly:

/app/node_modules/@onesignal/node-onesignal/dist/apis/exception.js:20
Oct 25 19:16:16Z myapp-name app/web.8         var _this = _super.call(this, "HTTP-Code: " + code + "\nMessage: " + JSON.stringify(body)) || this;
Oct 25 19:16:16Z myapp-name app/web.8                            ^
Oct 25 19:16:16Z myapp-name app/web.8 Error: HTTP-Code: 500
Oct 25 19:16:16Z myapp-name app/web.8 Message: "Unknown API Status Code!\nBody: \"[object Object]\""
Oct 25 19:16:16Z myapp-name app/web.8     at new ApiException (/app/node_modules/@onesignal/node-onesignal/dist/apis/exception.js:20:28)
Oct 25 19:16:16Z myapp-name app/web.8     at DefaultApiResponseProcessor.<anonymous> (/app/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:781:31)
Oct 25 19:16:16Z myapp-name app/web.8     at step (/app/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:46:23)
Oct 25 19:16:16Z myapp-name app/web.8     at Object.next (/app/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:27:53)

OR

Oct 22 18:35:00Z myapp-name app/web.8 			reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
Oct 22 18:35:00Z myapp-name app/web.8 			       ^
Oct 22 18:35:00Z myapp-name app/web.8 FetchError: request to https://onesignal.com/api/v1/notifications failed, reason: connect ETIMEDOUT 104.18.225.52:443
Oct 22 18:35:00Z myapp-name app/web.8     at ClientRequest.<anonymous> (/app/node_modules/node-fetch/lib/index.js:1483:11)
Oct 22 18:35:00Z myapp-name app/web.8     at ClientRequest.emit (node:events:513:28)
Oct 22 18:35:00Z myapp-name app/web.8     at TLSSocket.socketErrorListener (node:_http_client:494:9)
Oct 22 18:35:00Z myapp-name app/web.8     at TLSSocket.emit (node:events:513:28)
Oct 22 18:35:00Z myapp-name app/web.8     at emitErrorNT (node:internal/streams/destroy:157:8)
Oct 22 18:35:00Z myapp-name app/web.8     at emitErrorCloseNT (node:internal/streams/destroy:122:3)
Oct 22 18:35:00Z myapp-name app/web.8     at processTicksAndRejections (node:internal/process/task_queues:83:21) {
Oct 22 18:35:00Z myapp-name app/web.8   type: 'system',
Oct 22 18:35:00Z myapp-name app/web.8   errno: 'ETIMEDOUT',
Oct 22 18:35:00Z myapp-name app/web.8   code: 'ETIMEDOUT'

with the awaited function being:

const sendNotif = async (content, listUids, notification) => {
  if (!content || !listUids || listUids.length === 0) return
  return new Promise(async (resolve) => {
    const app_key_provider = {
        getToken() {
            return process.env.ONESIGNAL_REST_API_KEY
        }
    };
    const configuration = OneSignal.createConfiguration({
      authMethods: {
          app_key: {
            tokenProvider: app_key_provider
          }
      }
    });
    const client = new OneSignal.DefaultApi(configuration);
    let notification = new OneSignal.Notification();
    notification.app_id = process.env.ONESIGNAL_APP_ID;
    notification.include_player_ids = listUids
    notification.contents = {
      en: content
    };
    const { id } = await client.createNotification(notification);
    resolve(id)
  })
}

Code of Conduct

  • I agree to follow this project's Code of Conduct

Repo doesn't reference NPM

The About Repo section doesn't reference the package's location on npm. We should update the website attribute to point users to the relevant docs.

[question]: Getting module not found when using Typescript

How can we help?

I am getting the following error when trying to run my typescript project.

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/aslampr07/Desktop/NRIBrokers/nri-server/node_modules/@onesignal/node-onesignal/dist/index.js' imported from /home/aslampr07/Desktop/NRIBrokers/nri-server/dist/utils/notifications.js

Looking at the node_modules, the dist directory is not presented there. It should have present there when installing?

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: Critical Notifications not working

How can we help?

If I use the onesignal "Send message" GUI form on the website I can get a critical alert on my test phone just fine. This tells me my app is fine. However, through the API with this plugin I can't get critical notifications to work. See code below. The notification with the code below will come through if I turn DND off. However, with DND I get nothing even though I should.

const notification = new OneSignal.Notification();
notification.app_id = ONESIGNAL_APP_ID;
notification.include_player_ids = [pushId];
notification.include_player_ids = [pushId];
notification.priority = 10;
notification.ios_interruption_level = "critical";
notification.mutable_content = true;
notification.data = {
type: "test"
}
notification.android_channel_id = getAudioTag(sound).android;

notification.ios_sound = getAudioTag(sound).ios;
notification.contents = {
    en: "Test Push Notification @ " + pageGetTime((Date.now() / 1000), users.getUserData(userId).timeFormat)
};
notification.headings = {
    "en": "Test"
}

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: OneSignal integration failing intermittently when deployed on Vercel

What happened?

I'm integrating OneSignal for push notifications in my Next.js application. Everything works perfectly in the local environment. However, after deploying to Vercel, the notifications fail intermittently, especially on the first attempt.

Steps to reproduce?

1. [Clone the repository](https://github.com/prisma-korea/prisma-nextjs-rsc) and install `"@onesignal/node-onesignal": "^2.0.1-beta1"`. Set up the necessary environment variables (ONESIGNAL_APP_ID, ONESIGNAL_REST_API_KEY).

2. Create serverless function

    ```ts
    import * as OneSignal from '@onesignal/node-onesignal';
    import type {NextApiRequest, NextApiResponse} from 'next';
    
    type Reply =
      | {
          key: string;
          message: string;
        }
      | {id: string; description?: string | null};
    
    export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse<Reply>,
    ): Promise<void> {
      const {body, method} = req;
    
      const createNotification = async (
        notification: Omit<OneSignal.Notification, 'app_id'>,
      ): Promise<OneSignal.CreateNotificationSuccessResponse | undefined> => {
        const {ONESIGNAL_APP_ID, ONESIGNAL_REST_API_KEY} = process.env;
    
        try {
          const configuration = OneSignal.createConfiguration({
            authMethods: {
              app_key: {
                tokenProvider: {
                  getToken() {
                    return ONESIGNAL_REST_API_KEY as string;
                  },
                },
              },
            },
          });
    
          const client = new OneSignal.DefaultApi(configuration);
    
          return client.createNotification({
            ...notification,
            app_id: ONESIGNAL_APP_ID as string,
          });
        } catch (e) {
          // eslint-disable-next-line no-console
          console.log(e);
        }
      };
    
      switch (method) {
        case 'POST':
          const userId = <string>body.userId;
          const message = <string>body.message;
          const data = <Record<string, string>>body.data;
    
          if (!userId || !message) {
            res.status(500).send({
              key: 'BAD_REQUEST',
              message: 'userId and message are required',
            });
    
            return;
          }
    
          const notification: Parameters<typeof createNotification>[0] = {
            thread_id: 'admin',
            android_group: 'admin',
            include_external_user_ids: [userId],
            contents: {en: message},
            data,
          };
    
          createNotification(notification);
    
          res.status(200).send({
            key: 'SUCCESS',
            message: 'Successfully sent notification',
          });
          break;
        default:
          res.status(404).end();
      }
    }
    ```

2. Deploy the application to Vercel.

3. Try sending a notification through the provided endpoint in the deployed application.

4. Observe that it often fails on the first attempt and works intermittently after that.

What did you expect to happen?

I expected the OneSignal notifications to work seamlessly and consistently when deployed on Vercel, just as they do in the local environment.

Relevant log output

Screenshot 2023-07-23 at 11 13 51 PM

Code of Conduct

  • I agree to follow this project's Code of Conduct

REST API create notification returns 403 Forbidden error with Cloudflare Recaptcha html

Description

This is the link to my sample code repo
https://github.com/MuhammadUmarZahid/one-signal-node

I am trying to send OneSignal notifications from the node project using REST API provided by OneSignal.
Everything seemed to be working till yesterday. All of sudden today the endpoint:

/api/v1/notifications

started returning in response:

{
status: 403,
statusText: 'Forbidden',
data: ...
.....
}

The data key in the response had cloudflare html page which shows recaptcha. I dont know how should i solve the recaptcha on the server without opening a browser.

The same error started popping in my android app registered against the same app id on the onesignal dashboard.

Please help me with this as i want to go into production asap,

Steps to Reproduce

Unknown but maybe i sent more requests to the onesignal server in the past 2 to 3 days which caused the cloudflare ddos protection to trigger.

Environment

node version 16.4.0
npm version 7.18.1
Visual Studio Code 1.64.1
Axios 0.25.0

[Bug]:

What happened?

If I use the getPlayers() API, it throws a none readable exception. All other APIs work.

Steps to reproduce?

1. Install @onesignal/node-onesignal
2. call `client.getPlayers(appid, '300', 0);`

What did you expect to happen?

Retrieve a list of players.

Relevant log output

Message: "Unknown API Status Code!\nBody: \"[object Object]\""
    at new ApiException (/Users/tonyschumacher/git/terra-backend/node_modules/@onesignal/node-onesignal/apis/exception.ts:12:9)
    at DefaultApiResponseProcessor.<anonymous> (/Users/tonyschumacher/git/terra-backend/node_modules/@onesignal/node-onesignal/apis/DefaultApi.ts:1577:15)
    at step (/Users/tonyschumacher/git/terra-backend/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:46:23)
    at Object.next (/Users/tonyschumacher/git/terra-backend/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:27:53)
    at /Users/tonyschumacher/git/terra-backend/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:21:71
    at new Promise (<anonymous>)
    at __awaiter (/Users/tonyschumacher/git/terra-backend/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:17:12)
    at DefaultApiResponseProcessor.getPlayers (/Users/tonyschumacher/git/terra-backend/node_modules/@onesignal/node-onesignal/dist/apis/DefaultApi.js:1199:16)
    at /Users/tonyschumacher/git/terra-backend/node_modules/@onesignal/node-onesignal/types/ObservableAPI.ts:456:107
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 400,
  body: 'Unknown API Status Code!\nBody: "[object Object]"'
}


### Code of Conduct

- [X] I agree to follow this project's Code of Conduct

[question]: iOS time-sensitive notifications

How can we help?

Hi, how do I send programmatically iOS time-sensitive notifications (the ones with "interruption-level" set to "time-sensitive")? I can't find a reference to those in the docs. I see it is possible with the web UI.

Thank you!

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Getting error 400 without any specific details

What's on your mind?

How should I understand what should be changed in my request?

Error: HTTP-Code: 400
Message: Bad Request
Body: {"errors":[{}]}

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Docs]: Improve error display | Add better samples for email and sms notifications

What's on your mind?

I had to use axios in order to figure out what's happening in my 400 status code request due to errors being show as GenericErrorErrorsInner without clear error messages.

It would be simpler if docs had a sample of sms notification requiring sms_from prop, and an equivalent sample for email notification sending.

I would appreciate it if the documentation was improved in this regard.

Indeed, notification type not contains include_subscription_ids prop.

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: update node-fetch to 3.x

What's on your mind?

Am getting this warning now:

(node:59969) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)

This is a problem with node-fetch 2.x, not 3.x. Please update the dependency and release a new version

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Extend APIException to give more details

What's on your mind?

The SDK uses ApiException for sending API exceptions but clients can only read string from this object.
Clients should be able to easily get fields such as HTTP status code, headers, body, message, etc. that are generic to all requests. Status Code is specially useful for emitting metrics and quickly debugging.

API exception should have fields corresponding to them e.g. status_code, body, etc.

Code of Conduct

  • I agree to follow this project's Code of Conduct

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.