Skip to content
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

@commercetools/ts-client 2.0 throws javascript error on http error #761

Open
mvantellingen opened this issue Jul 26, 2024 · 20 comments
Open
Assignees
Labels
bug Something isn't working

Comments

@mvantellingen
Copy link

Describe the bug
I previously run into this issue: #647 but with the latest version (2.0) we now get the following error:

TypeError: Cannot read properties of undefined (reading 'error')
../../../node_modules/.pnpm/@[email protected][email protected]/node_modules/@commercetools/ts-client/dist/commercetools-ts-client.cjs.dev.js:1461:19

I think this is the relevant line

To Reproduce
Do a request which returns an error

@mvantellingen mvantellingen added the bug Something isn't working label Jul 26, 2024
@mvantellingen
Copy link
Author

PS. we (Lab Digital) have a shared slack channel, feel free to reach out to me.

@Engerim
Copy link
Contributor

Engerim commented Jul 29, 2024

I see a similiar issue but only when I use the createQueueMiddleware then we ofc queue a lot of requests and when we exceed the concurrency value of 10 in our case, the res is undefined hte process failed, if I deactivate the queue it works

@ajimae ajimae self-assigned this Aug 5, 2024
@ajimae
Copy link
Contributor

ajimae commented Aug 5, 2024

PS. we (Lab Digital) have a shared slack channel, feel free to reach out to me.

Hi @mvantellingen

Thanks for reporting this issue. Can you provide me with more details on the request that caused this error? if possible a code snippet will also work.

Thanks

@ajimae
Copy link
Contributor

ajimae commented Aug 5, 2024

I see a similiar issue but only when I use the createQueueMiddleware then we ofc queue a lot of requests and when we exceed the concurrency value of 10 in our case, the res is undefined hte process failed, if I deactivate the queue it works

Hi @Engerim

Can you provide a code snippet that caused this issue, in the mean time I will investigate it to see if I can reproduce it from my end.

Thanks once again for reporting this issue.

@ajimae
Copy link
Contributor

ajimae commented Aug 6, 2024

Currently working to find the root cause of this issue and I can confirm this issue doesn't exist in version 1.0.0 of the @commercetools/ts-client package.

I will continue working to fix it.

@Engerim
Copy link
Contributor

Engerim commented Aug 8, 2024

We are working just with a loop of promises where we send over 100 requests and in the promises and we use the concurrency middleware and set the value to 10 and it fails. it is just happening I will try on monday to replicate the issue in a smaller testcase

@ajimae
Copy link
Contributor

ajimae commented Aug 8, 2024

Hi @Engerim,

We raised a PR to fix this issue, once it's merge and we release a new version, this issue should be fixed.

Thanks

@ajimae
Copy link
Contributor

ajimae commented Aug 21, 2024

This is now fixed, please update to the latest version of the SDK. Thanks

@ajimae ajimae closed this as completed Aug 21, 2024
@miticm
Copy link

miticm commented Sep 9, 2024

Hi @ajimae, I am getting the error using the latest 2.0.4 version [0] TypeError: Cannot read properties of undefined (reading 'error') [0] at /node_modules/@commercetools/ts-client/dist/commercetools-ts-client.cjs.dev.js:1492:19 [0] at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
I am using the withAnonymousSessionFlow and performing some chained calls like this apiRoot .inStoreKeyWithStoreKeyValue({ storeKey: xxx" }) .me() .carts() .withId({ ID: cartId }) .post({ body: { version: version, actions: [myCartAddLineItemAction], }, }) .execute() and when an error occurs, the error above from the SDK will appear. when I was using the @commercetools/sdk-client-v2, it works fine, I am trying to migrate but have this issue

@ajimae ajimae reopened this Sep 9, 2024
@ajimae
Copy link
Contributor

ajimae commented Sep 9, 2024

Hi @miticm

I would like to know if you experience this error only on version 2.0.4. does it also occur in version prior to 2.0.4, can you check if this error also occur in version 2.0.3?

Also, I believe this issue is fixed here and a new patch version was released here as well.

You try this fixed version (2.0.2) and let us know if you still experience this error.

Thanks

@miticm
Copy link

miticm commented Sep 10, 2024

Hi @ajimae,

I also experience this error in 2.0.3 and 2.0.2. I am not using the ConcurrentModificationMiddleware though, so I am not sure if the fix is relevant

Thanks

@ajimae
Copy link
Contributor

ajimae commented Sep 10, 2024

Hi @miticm

Thanks for confirming the issue also exists in other versions of the SDK.

I will look into this and make a fix as soon as possible.

I will let you know, once it is done.

Thanks

@ajimae
Copy link
Contributor

ajimae commented Sep 13, 2024

Hi @miticm

I have been struggling to reproduce this issue, please can you share the code and configs that triggers this issues?

Preferably the client and the function and methods you are calling for making requests.

Thank you

@miticm
Copy link

miticm commented Sep 16, 2024

Hi @ajimae,

"@commercetools/checkout-browser-sdk": "^0.7.1",
"@commercetools/platform-sdk": "^7.13.0",
"@commercetools/ts-client": "^2.0.4",

here is the Client I use

export const getAnonymousSessionFlowApiRoot = ({
  token,
  refreshToken,
  expirationTime,
}: {
  token: string;
  refreshToken: string;
  expirationTime: number;
}): ApiRoot => {
  //AnonymousAuthMiddlewareOptions type not exist anymore in ts-client sdk
  const anonymousSession: AuthMiddlewareOptions = {
    host: oauthHost,
    projectKey,
    credentials: {
      clientId,
      clientSecret,
    },
    tokenCache: {
      get: () => {
        return {
          token,
          expirationTime,
          refreshToken,
        };
      },
      set: () => {},
    },
    scopes: [`manage_project:${projectKey}`],
  };

  const client = new ClientBuilder().withAnonymousSessionFlow(anonymousSession).withHttpMiddleware(httpOptions).build();
  return createApiBuilderFromCtpClient(client).withProjectKey({ projectKey });
};

and here is a call example

    apiRoot
    .inStoreKeyWithStoreKeyValue({ storeKey: "au-store" })
    .me()
    .activeCart()
    .get({
      queryArgs: {
        expand: "shippingInfo.shippingMethod",
      },
    })
    .execute();

and it will produce results with TypeError like these

[0] TypeError: Cannot read properties of undefined (reading 'error')
[0]     at /node_modules/@commercetools/ts-client/dist/commercetools-ts-client.cjs.dev.js:1492:19
[0]     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
[0]  POST /api/commercetool/cart/activeCart 200 in 1005ms
[0] TypeError: Cannot read properties of undefined (reading 'error')
[0]     at /node_modules/@commercetools/ts-client/dist/commercetools-ts-client.cjs.dev.js:1492:19
[0]     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
[0]  POST /api/commercetool/cart/addToCart 500 in 1810ms

@ajimae
Copy link
Contributor

ajimae commented Sep 16, 2024

Hi @ajimae,

"@commercetools/checkout-browser-sdk": "^0.7.1",
"@commercetools/platform-sdk": "^7.13.0",
"@commercetools/ts-client": "^2.0.4",

here is the Client I use

export const getAnonymousSessionFlowApiRoot = ({
  token,
  refreshToken,
  expirationTime,
}: {
  token: string;
  refreshToken: string;
  expirationTime: number;
}): ApiRoot => {
  //AnonymousAuthMiddlewareOptions type not exist anymore in ts-client sdk
  const anonymousSession: AuthMiddlewareOptions = {
    host: oauthHost,
    projectKey,
    credentials: {
      clientId,
      clientSecret,
    },
    tokenCache: {
      get: () => {
        return {
          token,
          expirationTime,
          refreshToken,
        };
      },
      set: () => {},
    },
    scopes: [`manage_project:${projectKey}`],
  };

  const client = new ClientBuilder().withAnonymousSessionFlow(anonymousSession).withHttpMiddleware(httpOptions).build();
  return createApiBuilderFromCtpClient(client).withProjectKey({ projectKey });
};

and here is a call example

    apiRoot
    .inStoreKeyWithStoreKeyValue({ storeKey: "au-store" })
    .me()
    .activeCart()
    .get({
      queryArgs: {
        expand: "shippingInfo.shippingMethod",
      },
    })
    .execute();

and it will produce results with TypeError like these

[0] TypeError: Cannot read properties of undefined (reading 'error')
[0]     at /node_modules/@commercetools/ts-client/dist/commercetools-ts-client.cjs.dev.js:1492:19
[0]     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
[0]  POST /api/commercetool/cart/activeCart 200 in 1005ms
[0] TypeError: Cannot read properties of undefined (reading 'error')
[0]     at /node_modules/@commercetools/ts-client/dist/commercetools-ts-client.cjs.dev.js:1492:19
[0]     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
[0]  POST /api/commercetool/cart/addToCart 500 in 1810ms

Hi @miticm,

I have seen the snippets.

I will take a look at it today and hopefully get it fixed.

Thanks

@ajimae
Copy link
Contributor

ajimae commented Sep 17, 2024

Hi @miticm,

I have been on this issue for sometime now and I still couldn't reproduce this on my end.

The following is the snippet I used for testing:

const { ClientBuilder } = require('@commercetools/ts-client');
const { createApiBuilderFromCtpClient } = require('@commercetools/platform-sdk')
const fetch = require('node-fetch');

function _tokenCache(val) {
  let initialVal = val
  return {
    get() {
      return initialVal
    },
    set(value) {
      initialVal = value
    }
  }
}

const tokenCache = _tokenCache({ token, expirationTime })
const projectKey = process.env.CTP_PROJECT_KEY;

const authMiddlewareOptions = {
  projectKey,
  host: 'https://auth.europe-west1.gcp.commercetools.com',
  credentials: {
    clientId: process.env.CTP_CLIENT_ID,
    clientSecret: process.env.CTP_CLIENT_SECRET
  },
  tokenCache,
  scopes: [`manage_project:${projectKey}`],
  httpClient: fetch
}

const httpMiddlewareOptions = {
  host: 'https://api.europe-west1.gcp.commercetools.com',
  // includeOriginalRequest: true,
  // maskSensitiveHeaderData: true,
  httpClient: fetch
}

const client = new ClientBuilder()
  .withProjectKey(projectKey)
  .withAnonymousSessionFlow(authMiddlewareOptions)
  .withHttpMiddleware(httpMiddlewareOptions)
  .build();

const apiRoot = createApiBuilderFromCtpClient(client).withProjectKey({ projectKey });

async function exec() {
  // create store
  // return apiRoot
  //   .stores()
  //   .post({ body: { key: 'xxx-test-key' } })
  //   .execute();

  // get carts
  // return apiRoot
  //   .inStoreKeyWithStoreKeyValue({ storeKey: 'xxx-test-key' })
  //   .me()
  //   .carts()
  //   .get({
  //     queryArgs: {
  //       expand: 'shippingInfo.shippingMethod',
  //     },
  //   }).execute();

  // create a cart in store
  // return apiRoot
  //   .inStoreKeyWithStoreKeyValue({ storeKey: 'xxx-test-key' })
  //   .me()
  //   .carts()
  //   .post({
  //     body: {
  //       currency: 'EUR'
  //     }
  //   }).execute();

  // get in-store active cart
  return apiRoot
    .inStoreKeyWithStoreKeyValue({ storeKey: 'xxx-test-key' })
    .me()
    .activeCart()
    .get({
      queryArgs: {
        expand: 'shippingInfo.shippingMethod'
      }
    }).execute();
}

exec()
  .then(data => {
    console.log(data)
  }).catch(e => {
    console.error(e)
  });

This is the error response when the active cart is not found.

Click to expand
 NotFound: URI not found: /{projectKey}/in-store/key=xxx-test-key/me/active-cart
    at createError (/Users/****/workspace/commercetools-sdk-typescript/packages/sdk-client/dist/commercetools-sdk-client-v2.cjs.dev.js:769:29)
    at /Users/****/workspace/commercetools-sdk-typescript/packages/sdk-client/dist/commercetools-sdk-client-v2.cjs.dev.js:940:25
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 404,
  statusCode: 404,
  status: 404,
  originalRequest: {
    baseUri: 'https://api.europe-west1.gcp.commercetools.com',
    method: 'GET',
    uriTemplate: '/{projectKey}/in-store/key={storeKey}/me/active-cart',
    pathVariables: {
      projectKey: '{projectKey}',
      storeKey: 'xxx-test-key'
    },
    headers: { Authorization: 'Bearer ********' },
    queryParams: undefined,
    uri: '/{projectKey}/in-store/key=xxx-test-key/me/active-cart'
  },
  retryCount: 0,
  headers: [Object: null prototype] {},
  body: {
    statusCode: 404,
    message: 'No active cart exists.',
    errors: [ [Object] ]
  }
}

I would suggest you do one or all the following to see if the issue still persists.

  • Create a new simple and fresh project from scratch.
  • Make a fresh install of the @commercetools/ts-client SDK.
  • Properly check your environment variables
  • If possible try out a new auth flow e.g ClientCredentialsFlow.
  • Try out the old client version to see if it works as expected.
  • Add a resolution field to your package.json to ensure the @commercetools/ts-client resolves to version 2.0.3 or newer.
  • Update node version.

Thank you.

@ajimae
Copy link
Contributor

ajimae commented Sep 18, 2024

Hi @miticm,

I am now able to reproduce this issue. The issue occurs when the execute() in the SDK is called concurrently.

I will raise a PR soon to fix this issue.

Thank you.

@ajimae
Copy link
Contributor

ajimae commented Sep 18, 2024

This should now be fixed

Don't hesitate to reopen if the issue still persists.

Thank you.

@ajimae ajimae closed this as completed Sep 18, 2024
@miticm
Copy link

miticm commented Sep 19, 2024

Hi @ajimae, the issue still exists after upgrading the packages

@ajimae ajimae reopened this Sep 19, 2024
@ajimae ajimae mentioned this issue Oct 7, 2024
3 tasks
@ajimae
Copy link
Contributor

ajimae commented Oct 9, 2024

Hi,

We made almost a complete rewrite of the internal logic of the v3 SDK, we just made a new (v2.1.0) release.

You can try to update to the latest version and let us know if this issue still exists.

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

4 participants