Skip to content

feat: add some type asserting validation function #1117

New issue

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

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

Already on GitHub? Sign in to your account

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,78 @@ Used for internal logging. Defaults to [`console`](https://developer.mozilla.org
<tbody>
</table>

### validateEventNameOrNames()

```js
validateEventNameOrNames(event);
```

<table width="100%">
<tbody valign="top">
<tr>
<td>
<code>event</code>
<em>
string | string[]
</em>
</td>
<td>
<strong>Required.</strong>
The event name or an array of event names to validate.
</td>
</tr>
</tbody>
</table>

Returns `true` if the provided event name(s) match a known event name; otherwise, returns `false`.

Example:

```js
const event = "user.created";
if (validateEventNameOrNames(event)) {
console.log("Event is valid!");
}
```

---

### validatePayload()

```js
validatePayload(input);
```

<table width="100%">
<tbody valign="top">
<tr>
<td>
<code>input</code>
<em>
Object
</em>
</td>
<td>
<strong>Required.</strong>
The JSON input to validate and type-cast to the event type. Should contain properties `name`, `id`, and `payload`.
</td>
</tr>
</tbody>
</table>

Returns a boolean value. If the input matches the expected structure and contains a valid event name, an ID, and a payload, it returns `true`. Otherwise, it returns `false`.

Example:

```js
const webhookData = { name: 'user.created', id: '12345', payload: { ... } };

if (validatePayload(webhookData)) {
// You can safely access webhookData as an EmitterWebhookEvent
console.log('Webhook payload is valid!');
}
```

### Webhook events

See the full list of [event types with example payloads](https://docs.github.com/developers/webhooks-and-events/webhook-events-and-payloads/).
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type {
export { createNodeMiddleware } from "./middleware/node/index.js";
export { createWebMiddleware } from "./middleware/web/index.js";
export { emitterEventNames } from "./generated/webhook-names.js";
export { validateEventNameOrNames, validatePayload } from "./validate-event.js";

// U holds the return value of `transform` function in Options
class Webhooks<TTransformed = unknown> {
Expand Down
63 changes: 63 additions & 0 deletions src/validate-event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { emitterEventNames } from "./generated/webhook-names.js";
import type { EmitterWebhookEventName, EmitterWebhookEvent } from "./types.js";

/**
* Validates if the provided event name or names are a know event name.
* If validation is successful, the types get narrowed to {@link EmitterWebhookEventName}.
*
* @param {string | string[]} event The event name or an array of event names to validate.
* @returns {event is EmitterWebhookEventName | EmitterWebhookEventName[]} True if the event name(s) are valid, otherwise false.
*/
export function validateEventNameOrNames(
event: string | string[],
): event is EmitterWebhookEventName | EmitterWebhookEventName[] {
if (Array.isArray(event)) {
return event.every((e) =>
emitterEventNames.includes(e as EmitterWebhookEventName),
);
}
return emitterEventNames.includes(event as EmitterWebhookEventName);
}

/**
* Validates the structure and type of a webhook payload and narrows the type to the corresponding event type.
*
* This function ensures that the provided input matches the expected structure of an event,
* including a valid event name, an ID, and a payload. If the validation passes, the input is
* narrowed to the specific {@link EmitterWebhookEvent} type.
*
* @template {EmitterWebhookEventName} TName The specific event name to validate against.
* @param {unknown} input The JSON input to validate and type-cast to the event type.
* @returns {input is EmitterWebhookEvent<TName>} True if the input is a valid event payload, otherwise false.
*/
export function validatePayload<TName extends EmitterWebhookEventName>(
input: unknown,
): input is EmitterWebhookEvent<TName> {
// Ensure the input is an object and has the necessary properties
if (
typeof input !== "object" ||
input === null ||
!("name" in input) ||
!("id" in input) ||
!("payload" in input)
) {
return false;
}

const typedInput = input as {
name: Object | undefined;
id: Object | undefined;
payload: Object | undefined;
};

if (
typeof typedInput.name !== "string" ||
typeof typedInput.id !== "string" ||
typeof typedInput.payload !== "object" ||
typedInput.payload === null
) {
return false;
}

return validateEventNameOrNames(typedInput.name);
}