contentful.js icon indicating copy to clipboard operation
contentful.js copied to clipboard

[QUESTION] - How to work with sync api and typescript?

Open hsheikhali1 opened this issue 3 years ago • 0 comments

Expected Behavior

We've decided to switch from the .getEntries api and are now going with the sync api. The data structure returned is similar to .getEntries

Actual Behavior

All fields are returned with their key as the locale ("en-US" etc..) and then the value.. making it kind of hard to parse with typescript...

NOTE I know this is intended, just want to know if there are any typescript examples to parse the entry fields in a nicer way..

Possible Solution

There is no real solution here but more-so an example. This has got me stuck for a while..

Steps to Reproduce

  1. initialize contentful client
  2. Use sync api to return all entries
  3. Realize each field for entries has a locale as its key.

Context

I am trying to parse out the fields, locale, and values to build out a structure for me to pass on to other parts of our application. Essentially normalizing the response.. Although the response from this API has literally everything I need.. It's hard to parse out with typescript. I was doing something similar with the sync assets and came up with this:

export const transformSyncApiResponse = (
	syncObject: Asset,
): AssetFileObject => {
	if ((syncObject.fields.file as Record<string, unknown>)["en-US"]) {
		return {
			url: ((syncObject.fields.file as unknown) as Record<
				string,
				Record<string, string>
			>)["en-US"].url,
			fileName: ((syncObject.fields.file as unknown) as Record<
				string,
				Record<string, string>
			>)["en-US"].fileName,
		};
	}

	return {
		url: syncObject.fields.file.url,
		fileName: syncObject.fields.file.fileName,
	};
};

I feel this is way too much just to get the fields I care about.. Now I am presented with the same situation with the entries returned from the sync api.

Does anyone have a better approach?? Sorry if this isn't the right place to ask this question.. not sure where else to ask.

Example response from sync api for entries...

 fields: {
    theme: { 'en-US': 'THEME' },
    thankYouTheme: { 'en-US': 'THEME' },
    metaTitle: {
      'en-US': 'Some Meta Title'
    },
    metaDescription: {
      'en-US': 'Some Meta Description'
    },
    metaOpenGraphImage: { 'en-US': [Object] },
    isLiveOnly: { 'en-US': true },
    webinarType: { 'en-US': 'Webinar' },
    webinarTitle: {
      'en-US': 'Some title for a webinar'
    },
  (...)

Environment

  • Language Version: 14.18.1
  • Package Manager Version: 6.14.15
  • Operating System: macOS Monterey
  • Package Version: 8.5.0
  • Which API are you using?: Management
  • Language Version:
  • Package Manager Version:
  • Browser Version:
  • Operating System:
  • Package Version:
  • Which API are you using?:

hsheikhali1 avatar Nov 01 '21 22:11 hsheikhali1