Skip to content

Commit

Permalink
fix: Remove i18n params from CMS calls if there is no i18n (#957)
Browse files Browse the repository at this point in the history
* Remove i18n params from CMS calls if there is no i18n

* Fix tests

* Push new snap

* Add failsafe for multilang CMS situations (#958)

* Add failsafe for multilang CMS situations

* Update tests snapshots

---------

Co-authored-by: Ionut Pasca <[email protected]>

---------

Co-authored-by: Ionut Pasca <[email protected]>
  • Loading branch information
TudorCe and pascaionut12345 authored Jan 22, 2025
1 parent 0456f08 commit f4c418e
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 34 deletions.
65 changes: 63 additions & 2 deletions packages/teleport-plugin-common/src/utils/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,7 @@ export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
allHeaders = allHeaders.concat(headersASTs)
}

const fetchAST = types.variableDeclaration('const', [
const fetchAST = types.variableDeclaration('let', [
types.variableDeclarator(
types.identifier('data'),
types.awaitExpression(
Expand Down Expand Up @@ -649,6 +649,66 @@ export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
),
])

// Fallback in case i18n interferes with normal CMS flows
const fallbackParams = JSON.parse(JSON.stringify(resource))
delete fallbackParams?.params?.locale
const fallbackUrlParamsDeclaration = generateParamsAST(fallbackParams?.params)
const assignmentOfNewUrlParams = types.expressionStatement(
types.assignmentExpression(
'=',
types.identifier('urlParams'),
types.objectExpression([...fallbackUrlParamsDeclaration])
)
)

const assignmentExpressionAST = types.expressionStatement(
types.assignmentExpression(
'=',
types.identifier('data'),
types.awaitExpression(
types.callExpression(types.identifier('fetch'), [
url,
types.objectExpression([
method,
...(allHeaders.length > 0
? [
types.objectProperty(
types.identifier('headers'),
types.objectExpression(allHeaders)
),
]
: []),
...(bodyParamsDecleration.length > 0 && resource?.method === 'POST'
? [
types.objectProperty(
types.identifier('body'),
types.callExpression(
types.memberExpression(
types.identifier('JSON'),
types.identifier('stringify')
),
[types.identifier('bodyParams')]
)
),
]
: []),
]),
])
)
)
)

const fallbackAST = types.ifStatement(
types.binaryExpression(
'!==', // The operator !==
types.memberExpression(
types.identifier('data'), // Access data
types.identifier('status') // Access data.status
),
types.numericLiteral(200) // Check if it is not equal to 200
),
types.blockStatement([assignmentOfNewUrlParams, assignmentExpressionAST])
)
const responseType = resource?.response?.type ?? 'json'
let responseJSONAST

Expand Down Expand Up @@ -718,7 +778,7 @@ export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
return [
...(urlParamsDecleration.length > 0
? [
types.variableDeclaration('const', [
types.variableDeclaration('let', [
types.variableDeclarator(
types.identifier('urlParams'),
types.objectExpression(urlParamsDecleration)
Expand All @@ -737,6 +797,7 @@ export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
]
: []),
fetchAST,
fallbackAST,
responseJSONAST,
]
}
Expand Down
3 changes: 2 additions & 1 deletion packages/teleport-plugin-next-static-props/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ export const createStaticPropsPlugin: ComponentPluginFactory<StaticPropsPluginCo
const getStaticPropsAST = generateInitialPropsAST(
uidl.outputOptions.initialPropsData,
resourceImportName,
resources.cache
resources.cache,
options.skipI18n
)

chunks.push({
Expand Down
50 changes: 30 additions & 20 deletions packages/teleport-plugin-next-static-props/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ import { StringUtils } from '@teleporthq/teleport-shared'
export const generateInitialPropsAST = (
initialPropsData: UIDLInitialPropsData,
resourceImportName: string,
globalCache: UIDLResources['cache']
globalCache: UIDLResources['cache'],
skipI18n?: boolean
) => {
const functionContentAST = types.blockStatement([
types.tryStatement(
types.blockStatement([...computePropsAST(initialPropsData, resourceImportName, globalCache)]),
types.blockStatement([
...computePropsAST(initialPropsData, resourceImportName, globalCache, skipI18n),
]),
types.catchClause(
types.identifier('error'),
types.blockStatement([
Expand Down Expand Up @@ -49,7 +52,8 @@ export const generateInitialPropsAST = (
const computePropsAST = (
initialPropsData: UIDLInitialPropsData,
resourceImportName: string,
globalCache: UIDLResources['cache']
globalCache: UIDLResources['cache'],
skipI18n?: boolean
) => {
const funcParams: types.ObjectProperty[] = Object.keys(
initialPropsData.resource?.params || {}
Expand Down Expand Up @@ -89,6 +93,28 @@ const computePropsAST = (
)
}

const localeAST = skipI18n
? []
: [
types.spreadElement(
types.logicalExpression(
'&&',
types.optionalMemberExpression(
types.identifier('context'),
types.identifier('locale'),
false,
true
),
types.objectExpression([
types.objectProperty(
types.identifier('locale'),
types.memberExpression(types.identifier('context'), types.identifier('locale'))
),
])
)
),
]

const declarationAST = types.variableDeclaration('const', [
types.variableDeclarator(
types.identifier('response'),
Expand All @@ -103,23 +129,7 @@ const computePropsAST = (
true
)
),
types.spreadElement(
types.logicalExpression(
'&&',
types.optionalMemberExpression(
types.identifier('context'),
types.identifier('locale'),
false,
true
),
types.objectExpression([
types.objectProperty(
types.identifier('locale'),
types.memberExpression(types.identifier('context'), types.identifier('locale'))
),
])
)
),
...localeAST,
...funcParams,
]),
])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,17 +81,6 @@ const Home = (props) => {
}
export default Home
export async function getStaticProps(context) {
const messages = (await import('/locales/' + context.locale + '.json'))
.default
return {
props: {
messages,
...context,
},
}
}
",
"fileType": "js",
"name": "index",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import * as types from '@babel/types'
export const createNextLocaleFetcherPlugin: ComponentPluginFactory<{}> = () => {
const nextLocaleFetcher: ComponentPlugin = async (structure) => {
const { chunks } = structure
if (structure.options.skipI18n) {
return structure
}

const jsxComponent = chunks.find((chunk) => chunk.name === 'jsx-component')
if (!jsxComponent) {
return structure
Expand Down
3 changes: 3 additions & 0 deletions packages/teleport-project-generator/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ describe('Generic Project Generator', () => {
extractedResources: {},
mapping: {},
skipValidation: true,
skipI18n: true,
}
)
expect(generator.pageGenerator.generateComponent).toBeCalledTimes(3)
Expand All @@ -147,6 +148,7 @@ describe('Generic Project Generator', () => {
extractedResources: {},
mapping: {},
skipValidation: true,
skipI18n: true,
}
)

Expand Down Expand Up @@ -204,6 +206,7 @@ describe('Generic Project Generator', () => {
projectRouteDefinition: uidl.root.stateDefinitions.route,
mapping: {},
skipValidation: true,
skipI18n: true,
}
)

Expand Down
1 change: 1 addition & 0 deletions packages/teleport-project-generator/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ export class ProjectGenerator implements ProjectGeneratorType {
mapping,
extractedResources: {},
skipValidation: true,
skipI18n: !uidl.internationalization,
...(uidl.resources &&
this.strategy?.resources?.path && {
resources: {
Expand Down
1 change: 1 addition & 0 deletions packages/teleport-types/src/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ export interface GeneratorOptions {
skipValidation?: boolean
isRootComponent?: boolean
skipNavlinkResolver?: boolean
skipI18n?: boolean
projectRouteDefinition?: UIDLRouteDefinitions
strategy?: ProjectStrategy
moduleComponents?: Record<string, ComponentUIDL>
Expand Down

0 comments on commit f4c418e

Please sign in to comment.