Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk): upper-case the method of a raw request in Go and JS
Yudhi Armyndharis76463ac0d4c0
diff --git a/sdk/go/client.go b/sdk/go/client.goindex 600555297..d9bf5465e 100644--- a/sdk/go/client.go+++ b/sdk/go/client.go@@ -279,6 +279,9 @@ func isIdempotentSendPath(path string) bool {// typed service path (rawPath false) also refuses an empty segment, which// means a required id was blank; a hand-written Do path may keep one.func (c *Client) doRaw(ctx context.Context, method, path string, query url.Values, body any, rawPath bool) ([]byte, string, error) {+ // net/http sends the method as written and the gateway answers 400 to a lowercase one. The idempotency+ // header and the retry policy compare the upper-case names as well.+ method = strings.ToUpper(method)if err := checkPathSegments(path, rawPath); err != nil {return nil, "", err}diff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex 55d700a12..6455b1925 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -1788,6 +1788,33 @@ func TestDoPathWithQueryAppendsQueryValues(t *testing.T) {}}+// net/http sends the method as written and the gateway answers 400 to a lowercase one, so Do upper-cases+// it. The idempotency header and the retry policy compare the upper-case names too.+func TestDoSendsTheMethodInUpperCase(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{}`}+ c := newTestClient(t, rt)+ for _, tc := range []struct{ given, want string }{+ {"get", "GET"}, {"post", "POST"}, {"put", "PUT"}, {"patch", "PATCH"}, {"delete", "DELETE"},+ {"Patch", "PATCH"}, {"PATCH", "PATCH"},+ } {+ rt.lastReq = nil+ if err := c.Do(context.Background(), tc.given, "/api/x", nil, nil, nil); err != nil {+ t.Fatalf("Do(%q): %v", tc.given, err)+ }+ if got := rt.lastReq.Method; got != tc.want {+ t.Errorf("Do(%q): the transport saw %q, want %q", tc.given, got, tc.want)+ }+ }++ ctx := WithIdempotencyKey(context.Background(), "k1")+ if err := c.Do(ctx, "post", "/api/sessions/s/messages/send-text", nil, map[string]string{"chatId": "x"}, nil); err != nil {+ t.Fatal(err)+ }+ if got := rt.lastReq.Header.Get("Idempotency-Key"); got != "k1" {+ t.Errorf("a lowercase post to a send route sent Idempotency-Key %q, want %q", got, "k1")+ }+}+func TestSendIdempotencyKey(t *testing.T) {rt := &recordTransport{status: 200, body: `{"messageId":"m","timestamp":1}`}c := newTestClient(t, rt, WithHeader("idempotency-key", "default"))diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.tsindex 40217dcef..306e75530 100644--- a/sdk/javascript/src/http.ts+++ b/sdk/javascript/src/http.ts@@ -208,12 +208,17 @@ async function send<T>(headers['Content-Type'] = 'application/json';headers['X-API-Key'] = config.apiKey;+ // fetch upper-cases GET, POST, PUT and DELETE itself but sends PATCH and any other verb as written, and the+ // gateway answers 400 to a lowercase method; a caller without the HttpMethod type can pass one. A missing+ // method stays undefined, which fetch sends as GET.+ const method = options.method?.toUpperCase();+// Called without a receiver: a platform fetch passed in as `fetch: globalThis.fetch` throws// "Illegal invocation" in browsers and Workers when invoked as a method of `config`.const doFetch = config.fetch;try {const res = await doFetch(url, {- method: options.method,+ method,headers,body: options.body !== undefined ? JSON.stringify(options.body) : undefined,signal: controller.signal,@@ -224,7 +229,7 @@ async function send<T>(});if (!res.ok) {- const context = `${options.method} ${options.path}`;+ const context = `${method} ${options.path}`;const apiError = await OpenWAApiError.fromResponse(res, context);throw classifyApiError(apiError.status, apiError.message, apiError.body, apiError.errorKind, apiError.headers);}diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.tsindex 75b23ebf3..d552e88ed 100644--- a/sdk/javascript/test/client.test.ts+++ b/sdk/javascript/test/client.test.ts@@ -650,6 +650,22 @@ describe('OpenWAClient', () => {expect(wire!.get('x-trace')).toBe('keep');});+ it('sends the method of a raw request in upper case, whatever the caller wrote', async () => {+ // fetch upper-cases GET, POST, PUT and DELETE itself but sends PATCH as written, and the gateway answers+ // 400 to a lowercase method; a caller without the HttpMethod type can pass one.+ const sent: Array<string | undefined> = [];+ const recordingFetch: FetchLike = async (_url, init) => {+ sent.push(init?.method);+ return new Response('[]', { status: 200 });+ };+ const c = new OpenWAClient({ baseUrl: 'http://localhost', apiKey: 'k', fetch: recordingFetch });+ for (const method of ['get', 'post', 'put', 'patch', 'delete', 'Patch', 'PATCH']) {+ await c.request({ method: method as never, path: '/api/sessions' });+ }+ await c.requestBytes({ method: 'patch' as never, path: '/api/sessions' });+ expect(sent).toEqual(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'PATCH', 'PATCH', 'PATCH']);+ });+it('calls the global fetch unbound from the client config when none is injected', async () => {// Browsers and Workers reject a fetch invoked as a method of another object ("Illegal invocation").vi.stubGlobal('fetch', function (this: unknown) {