-
Notifications
You must be signed in to change notification settings - Fork 0
Node SDK webhook handler #47
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
Open
cb-karthikp
wants to merge
27
commits into
main
Choose a base branch
from
node-webhook-handler
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
9ac5101
event and listners for webhook
cb-karthikp e396c2e
update type
cb-karthikp a4a3ba4
include pc1 events
cb-karthikp b6810d9
node webhook hbs changes
cb-karthikp 7419c12
add default webhook handler instance
cb-karthikp 583508f
Update index.d.ts.hbs
cb-karthikp 5b29303
Event type class name change
cb-karthikp 93f57bf
add Event type run-time export
cb-karthikp df23d80
moved un-handled out
cb-karthikp 24544c5
framwork agnostic request-response type
cb-karthikp 64c417c
Merge branch 'main' into node-webhook-handler
cb-karthikp 76d5496
SDK changes
cb-karthikp ec368d3
move default auth validation to util
cb-karthikp 6696142
add warning for no-auth webhook flow
cb-karthikp 24e07ef
add field validation
cb-karthikp 46822f1
better error management
cb-karthikp b69976a
add deprecation message and strict-content type
cb-karthikp 0940ac9
add comments
cb-karthikp c4b6050
Merge branch 'main' into node-webhook-handler
cb-karthikp a545d0a
Update test case
cb-karthikp 9087f91
Merge branch 'main' into node-webhook-handler
cb-karthikp fc49503
fix testcase
cb-karthikp a2b132e
Fixed an issue with the webhook content for hidden resources.
cb-alish 228ce2e
add support on error.
cb-karthikp 0f74017
Merge branch 'main' into node-webhook-handler
cb-karthikp 90cf45e
Fix TypeScriptTypingV3Tests for updated webhook
cb-karthikp bc4769d
Webhook error changes
cb-karthikp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
152 changes: 152 additions & 0 deletions
152
src/main/java/com/chargebee/sdk/node/webhook/WebhookGenerator.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| package com.chargebee.sdk.node.webhook; | ||
|
|
||
| import com.chargebee.openapi.Attribute; | ||
| import com.chargebee.openapi.Resource; | ||
| import com.chargebee.openapi.Spec; | ||
| import com.chargebee.sdk.FileOp; | ||
| import com.github.jknack.handlebars.Template; | ||
| import java.io.IOException; | ||
| import java.util.*; | ||
|
|
||
| public class WebhookGenerator { | ||
|
|
||
| private static List<String> getEventResourcesForAEvent(Resource eventResource) { | ||
| List<String> resources = new ArrayList<>(); | ||
| if (eventResource != null) { | ||
| for (Attribute attribute : eventResource.attributes()) { | ||
| if (attribute.name.equals("content")) { | ||
| attribute | ||
| .attributes() | ||
| .forEach( | ||
| (innerAttribute -> { | ||
| String ref = innerAttribute.schema.get$ref(); | ||
| if (ref != null && ref.contains("/")) { | ||
| String schemaName = ref.substring(ref.lastIndexOf("/") + 1); | ||
| resources.add(schemaName); | ||
| } | ||
| })); | ||
| } | ||
| } | ||
| } | ||
| return resources; | ||
| } | ||
|
|
||
| public static List<FileOp> generate( | ||
| String outputDirectoryPath, | ||
| Spec spec, | ||
| Template eventTypesTemplate, | ||
| Template contentTemplate, | ||
| Template handlerTemplate, | ||
| Template authTemplate) | ||
| throws IOException { | ||
| final String webhookDirectoryPath = "/webhook"; | ||
| List<FileOp> fileOps = new ArrayList<>(); | ||
| // Ensure webhook directory exists | ||
| fileOps.add(new FileOp.CreateDirectory(outputDirectoryPath, webhookDirectoryPath)); | ||
|
|
||
| // Include deprecated webhook events (like PCV1) since customers may still receive them | ||
| var webhookInfo = spec.extractWebhookInfo(true); | ||
| var eventSchema = spec.resourcesForEvents(); | ||
|
|
||
| if (webhookInfo.isEmpty()) { | ||
| return fileOps; | ||
| } | ||
|
|
||
| List<Map<String, Object>> events = new ArrayList<>(); | ||
| Set<String> seenTypes = new HashSet<>(); | ||
| Set<String> uniqueImports = new HashSet<>(); | ||
|
|
||
| // Compute models directory by taking parent of webhook output dir | ||
| java.io.File webhookDir = new java.io.File(outputDirectoryPath + webhookDirectoryPath); | ||
| java.io.File chargebeeRoot = webhookDir.getParentFile(); | ||
|
|
||
| for (Map<String, String> info : webhookInfo) { | ||
| String type = info.get("type"); | ||
| if (seenTypes.contains(type)) { | ||
| continue; | ||
| } | ||
| seenTypes.add(type); | ||
|
|
||
| String resourceSchemaName = info.get("resource_schema_name"); | ||
| Resource matchedSchema = | ||
| eventSchema.stream() | ||
| .filter(schema -> schema.name.equals(resourceSchemaName)) | ||
| .findFirst() | ||
| .orElse(null); | ||
|
|
||
| List<String> allSchemas = getEventResourcesForAEvent(matchedSchema); | ||
| List<String> schemaImports = new ArrayList<>(); | ||
|
|
||
| for(String schema : allSchemas) { | ||
| // In Node we import Resource classes/interfaces. | ||
| // Assuming 'Customer' -> 'Customer' in types | ||
| schemaImports.add(schema); | ||
| uniqueImports.add(schema); | ||
| } | ||
|
|
||
| Map<String, Object> params = new HashMap<>(); | ||
| params.put("type", type); | ||
| params.put("resource_schemas", schemaImports); | ||
| events.add(params); | ||
| } | ||
|
|
||
| events.sort(Comparator.comparing(e -> e.get("type").toString())); | ||
|
|
||
| // event_types.ts | ||
| { | ||
| Map<String, Object> ctx = new HashMap<>(); | ||
| ctx.put("events", events); | ||
| fileOps.add( | ||
| new FileOp.WriteString( | ||
| outputDirectoryPath + webhookDirectoryPath, | ||
| "event_types.ts", | ||
| eventTypesTemplate.apply(ctx) | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| // content.ts | ||
| { | ||
| Map<String, Object> ctx = new HashMap<>(); | ||
| ctx.put("events", events); | ||
| List<String> importsList = new ArrayList<>(uniqueImports); | ||
| Collections.sort(importsList); | ||
| ctx.put("unique_imports", importsList); | ||
|
|
||
| fileOps.add( | ||
| new FileOp.WriteString( | ||
| outputDirectoryPath + webhookDirectoryPath, | ||
| "content.ts", | ||
| contentTemplate.apply(ctx) | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| // handler.ts | ||
| { | ||
| Map<String, Object> ctx = new HashMap<>(); | ||
| ctx.put("events", events); | ||
| fileOps.add( | ||
| new FileOp.WriteString( | ||
| outputDirectoryPath + webhookDirectoryPath, | ||
| "handler.ts", | ||
| handlerTemplate.apply(ctx) | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| // auth.ts | ||
| { | ||
| fileOps.add( | ||
| new FileOp.WriteString( | ||
| outputDirectoryPath + webhookDirectoryPath, | ||
| "auth.ts", | ||
| authTemplate.apply("") | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| return fileOps; | ||
| } | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| export const basicAuthValidator = (validateCredentials: (username: string, password: string) => boolean) => { | ||
| return (headers: Record<string, string | string[] | undefined>) => { | ||
| const authHeader = headers['authorization'] || headers['Authorization']; | ||
|
|
||
| if (!authHeader) { | ||
| throw new Error("Invalid authorization header"); | ||
| } | ||
|
|
||
| const authStr = Array.isArray(authHeader) ? authHeader[0] : authHeader; | ||
| if (!authStr) { | ||
| throw new Error("Invalid authorization header"); | ||
| } | ||
|
|
||
| const parts = authStr.split(' '); | ||
| if (parts.length !== 2 || parts[0] !== 'Basic') { | ||
| throw new Error("Invalid authorization header"); | ||
| } | ||
|
|
||
| const credentials = Buffer.from(parts[1], 'base64').toString().split(':'); | ||
| if (credentials.length !== 2) { | ||
| throw new Error("Invalid credentials"); | ||
| } | ||
|
|
||
| if (!validateCredentials(credentials[0], credentials[1])) { | ||
| throw new Error("Invalid credentials"); | ||
| } | ||
| }; | ||
| }; | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| declare module 'chargebee' { | ||
| {{#each unique_imports}} | ||
| export interface {{this}} {} | ||
| {{/each}} | ||
| } | ||
|
|
||
| {{#each events}} | ||
| export interface {{snakeCaseToPascalCase type}}Content { | ||
| {{#each resource_schemas}} | ||
| {{camelCase this}}: import('chargebee').{{this}}; | ||
| {{/each}} | ||
| } | ||
|
|
||
| {{/each}} | ||
| export interface WebhookEvent { | ||
| id: string; | ||
| occurred_at: number; | ||
| source: string; | ||
| user?: string; | ||
| webhook_status: string; | ||
| webhook_failure_reason?: string; | ||
| webhooks?: any[]; | ||
| event_type: string; | ||
| api_version: string; | ||
| content: any; | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| export enum EventType { | ||
| {{#each events}} | ||
| {{constantCase type}} = '{{type}}', | ||
| {{/each}} | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| import { EventType } from './event_types.js'; | ||
| import { | ||
| {{#each events}} | ||
| {{snakeCaseToPascalCase type}}Content, | ||
| {{/each}} | ||
| WebhookEvent | ||
| } from './content.js'; | ||
|
|
||
| export interface WebhookHandlers { | ||
| {{#each events}} | ||
| on{{snakeCaseToPascalCase type}}?: (event: WebhookEvent & { content: {{snakeCaseToPascalCase type}}Content }) => Promise<void>; | ||
| {{/each}} | ||
| } | ||
|
|
||
| export class WebhookHandler { | ||
| private _handlers: WebhookHandlers = {}; | ||
|
|
||
| /** | ||
| * Optional callback for unhandled events. | ||
| */ | ||
| onUnhandledEvent?: (event: WebhookEvent) => Promise<void>; | ||
|
|
||
| /** | ||
| * Optional callback for errors during processing. | ||
| */ | ||
| onError?: (error: any) => void; | ||
|
|
||
| /** | ||
| * Optional validator for request headers. | ||
| */ | ||
| requestValidator?: (headers: Record<string, string | string[] | undefined>) => void; | ||
|
|
||
| constructor(handlers: WebhookHandlers = {}) { | ||
| this._handlers = handlers; | ||
| } | ||
|
|
||
| {{#each events}} | ||
| set on{{snakeCaseToPascalCase type}}(handler: ((event: WebhookEvent & { content: {{snakeCaseToPascalCase type}}Content }) => Promise<void>) | undefined) { | ||
| this._handlers.on{{snakeCaseToPascalCase type}} = handler; | ||
| } | ||
|
|
||
| get on{{snakeCaseToPascalCase type}}() { | ||
| return this._handlers.on{{snakeCaseToPascalCase type}}; | ||
| } | ||
|
|
||
| {{/each}} | ||
|
|
||
| async handle(body: string | object, headers?: Record<string, string | string[] | undefined>): Promise<void> { | ||
| try { | ||
| if (this.requestValidator && headers) { | ||
| this.requestValidator(headers); | ||
| } | ||
|
|
||
| let event: WebhookEvent; | ||
| if (typeof body === 'string') { | ||
| event = JSON.parse(body); | ||
| } else { | ||
| event = body as WebhookEvent; | ||
| } | ||
|
|
||
| const eventType = event.event_type; | ||
|
|
||
| switch (eventType) { | ||
| {{#each events}} | ||
| case EventType.{{constantCase type}}: | ||
| if (this._handlers.on{{snakeCaseToPascalCase type}}) { | ||
| await this._handlers.on{{snakeCaseToPascalCase type}}(event as WebhookEvent & { content: {{snakeCaseToPascalCase type}}Content }); | ||
| return; | ||
| } | ||
| break; | ||
| {{/each}} | ||
| } | ||
|
|
||
| if (this.onUnhandledEvent) { | ||
| await this.onUnhandledEvent(event); | ||
| } | ||
| } catch (err) { | ||
| if (this.onError) { | ||
| this.onError(err); | ||
| } else { | ||
| throw err; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.