diff --git a/packages/sdk/src/server/index.ts b/packages/sdk/src/server/index.ts index bf9a6f9521a84..d7ed3209c3cb8 100644 --- a/packages/sdk/src/server/index.ts +++ b/packages/sdk/src/server/index.ts @@ -258,6 +258,11 @@ interface RequestOptions extends Omit { * Headers to include in the request. */ headers?: Record; + + /** + * The URL to make the request to. + */ + baseURL?: string; } /** @@ -284,7 +289,7 @@ class ServerClient { environment?: string; secretKey: string; publicKey: string; - oauthClient: ClientCredentials; + oauthClient?: ClientCredentials; oauthToken?: AccessToken; baseURL: string; @@ -339,6 +344,10 @@ class ServerClient { } async _oauthAuthorizationHeader(): Promise { + if (!this.oauthClient) { + throw new Error("OAuth client not configured"); + } + if (!this.oauthToken || this.oauthToken.expired()) { this.oauthToken = await this.oauthClient.getToken({}); } @@ -364,9 +373,10 @@ class ServerClient { headers: customHeaders, body, method = "GET", + baseURL = this.baseURL, ...fetchOpts } = opts; - const url = new URL(`${this.baseURL}${path}`); + const url = new URL(`${baseURL}${path}`); if (params) { Object.entries(params).forEach(([ @@ -615,4 +625,51 @@ class ServerClient { method: "GET", }); } + + /** + * Invokes a workflow using the URL of its HTTP interface(s), by sending an + * HTTP POST request with the provided body. + * + * @param url - The URL of the workflow's HTTP interface. + * @param opts - The options for the request. + * @param opts.body - The body of the request. It must be a JSON-serializable + * value (e.g. an object, `null`, a string, etc.). + * @param opts.headers - The headers to include in the request. Note that the + * `Authorization` header will always be set with an OAuth access token + * retrieved by the client. + * + * @returns A promise resolving to the response from the workflow. + * + * @example + * ```typescript + * const response: JSON = await client.invokeWorkflow( + * "https://eoy64t2rbte1u2p.m.pipedream.net", + * { + * body: { + * foo: 123, + * bar: "abc", + * baz: null, + * }, + * headers: { + * "Accept": "application/json", + * }, + * }, + * ); + */ + async invokeWorkflow(url: string, opts: RequestOptions = {}): Promise { + const { + body = null, + headers = {}, + } = opts; + + return this._makeRequest("", { + baseURL: url, + method: "POST", + headers: { + ...headers, + "Authorization": await this._oauthAuthorizationHeader(), + }, + body: JSON.stringify(body), + }); + } }