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

Split exports to client/server/common #474 #475

Merged
merged 2 commits into from
Feb 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
/*.map
/baseMappings.js
/client.js
/server.js
/common/
/guillotine/
/index.js
Expand Down Expand Up @@ -81,4 +82,4 @@ yarn-debug.log*
yarn-error.log*

# No permanent docs yet, only temporary used by madge
/docs/
/docs/
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"access": "public"
},
"scripts": {
"clean": "del-cli *.d.ts *.js.map baseMappings.* client.* common coverage index.* enonic-nextjs-adapter-*.tgz guillotine i18n query types utils views dist",
"clean": "del-cli *.d.ts *.js.map baseMappings.* client.* server.* common coverage index.* enonic-nextjs-adapter-*.tgz guillotine i18n query types utils views dist",
"build": "tsc",
"release": "tsc --outDir ./dist && npx --yes cpy-cli package.json README.md ./dist",
"check:types": "tsc --noEmit",
Expand Down
28 changes: 15 additions & 13 deletions src/common/env.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,39 @@
import {ENV_VARS} from './constants';

const isServer = typeof window === 'undefined';

// IMPORTANT:
// NEXT_PUBLIC_ vars should be explicitly referenced to be made available on the client side (substituted with constants) !!!
/** URL to the guillotine API */
export const API_URL = (process.env[ENV_VARS.API_URL] || process.env[`NEXT_PUBLIC_${ENV_VARS.API_URL}`]);
export const API_URL = isServer ? process.env[ENV_VARS.API_URL] : process.env['NEXT_PUBLIC_ENONIC_API'];

/** Optional utility value - defining in one place the name of the target app (the app that defines the content types, the app name is therefore part of the content type strings used both in typeselector and in query introspections) */
export const APP_NAME = (process.env[ENV_VARS.APP_NAME] || process.env[`NEXT_PUBLIC_${ENV_VARS.APP_NAME}`]);
export const APP_NAME = isServer ? process.env[ENV_VARS.APP_NAME] : process.env['NEXT_PUBLIC_ENONIC_APP_NAME'];

/** Optional utility value - derived from APP_NAME, only with underscores instead of dots */
export const APP_NAME_UNDERSCORED = (APP_NAME || '').replace(/\./g, '_');

/** Optional utility value - derived from APP_NAME, only with dashes instead of dots */
export const APP_NAME_DASHED = (APP_NAME || '').replace(/\./g, '-');

const mode = process.env.MODE || process.env.NEXT_PUBLIC_MODE;
const mode = isServer ? process.env.MODE : process.env.NEXT_PUBLIC_MODE;

export const IS_DEV_MODE = (mode === 'development');

/** Locales and Enonic XP projects correspondence list */
export const PROJECTS = (process.env[ENV_VARS.PROJECTS] || process.env[`NEXT_PUBLIC_${ENV_VARS.PROJECTS}`]);
export const PROJECTS = isServer ? process.env[ENV_VARS.PROJECTS] : process.env['NEXT_PUBLIC_ENONIC_PROJECTS'];

const requiredConstants = {
[ENV_VARS.APP_NAME]: APP_NAME,
[ENV_VARS.API_URL]: API_URL,
[ENV_VARS.PROJECTS]: PROJECTS,
};

if (typeof window === 'undefined') {
// Verify required values on server-side only
Object.keys(requiredConstants).forEach((key: string) => {
const val = requiredConstants[key];
if (!val) {
throw new Error(`Environment variable '${key}' is missing (from .env?)`);
}
});
}
// Verify required values on server-side only
Object.keys(requiredConstants).forEach((key: string) => {
const val = requiredConstants[key];
if (!val) {
throw new Error(`Environment variable '${isServer ? '' : 'NEXT_PUBLIC_'}${key}' is missing (from .env?)`);
}
});

6 changes: 3 additions & 3 deletions src/guillotine/fetchContent.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type {ComponentDescriptor, ContentFetcher, Context, FetchContentResult} from '../types';
import type {ComponentDescriptor, Context, FetchContentResult} from '../types';


import {headers} from 'next/headers';
Expand Down Expand Up @@ -42,7 +42,7 @@ import {createMetaData} from './createMetaData';
* @param context object from Next, contains .query info
* @returns FetchContentResult object: {data?: T, error?: {code, message}}
*/
export const fetchContent: ContentFetcher = async (context: Context): Promise<FetchContentResult> => {
export async function fetchContent(context: Context): Promise<FetchContentResult> {
const {locale, locales, defaultLocale} = getRequestLocaleInfo(context);

// ideally we only want to set headers in draft mode,
Expand Down Expand Up @@ -247,4 +247,4 @@ export const fetchContent: ContentFetcher = async (context: Context): Promise<Fe
}
return errorResponse(error.code, error.message);
}
};
}
13 changes: 4 additions & 9 deletions src/guillotine/fetchFromApi.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
import type {
ContentApiBaseBody,
GuillotineResponse,
GuillotineResponseJson,
ProjectLocaleConfig,
} from '../types';
import type {ContentApiBaseBody, GuillotineResponse, GuillotineResponseJson, ProjectLocaleConfig} from '../types';


/** Generic fetch */
export const fetchFromApi = async <Data = Record<string,unknown>>(
export async function fetchFromApi<Data = Record<string, unknown>>(
apiUrl: string,
body: ContentApiBaseBody,
projectConfig: ProjectLocaleConfig,
headers?: {},
method = 'POST',
) => {
) {
const options = {
method,
headers: {
Expand Down Expand Up @@ -71,4 +66,4 @@ export const fetchFromApi = async <Data = Record<string,unknown>>(
}

return json;
};
}
12 changes: 4 additions & 8 deletions src/guillotine/fetchGuillotine.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import type {
ContentApiBaseBody,
GuillotineResult,
ProjectLocaleConfig,
} from '../types';
import type {ContentApiBaseBody, GuillotineResult, ProjectLocaleConfig} from '../types';


import {fetchFromApi} from './fetchFromApi';


/** Guillotine-specialized fetch, using the generic fetch above */
export const fetchGuillotine = async <Data = Record<string,unknown>>(
export async function fetchGuillotine<Data = Record<string, unknown>>(
contentApiUrl: string,
body: ContentApiBaseBody,
projectConfig: ProjectLocaleConfig,
headers?: {},
): Promise<GuillotineResult> => {
): Promise<GuillotineResult> {
if (typeof body.query !== 'string' || !body.query.trim()) {
return {
error: {
Expand Down Expand Up @@ -62,4 +58,4 @@ export const fetchGuillotine = async <Data = Record<string,unknown>>(
return {error: {code: 'Client-side error', message: err.message}};
}
});
};
}
7 changes: 2 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,7 @@ export {
XP_REQUEST_TYPE,
} from './common/constants';

export {fetchContent} from './guillotine/fetchContent';
export {fetchContentPathsForAllLocales} from './guillotine/fetchContentPathsForAllLocales';
export {fetchContentPathsForLocale} from './guillotine/fetchContentPathsForLocale';
export {fetchFromApi} from './guillotine/fetchFromApi';
export {fetchGuillotine} from './guillotine/fetchGuillotine';

export {richTextQuery} from './guillotine/metadata/richTextQuery';
export {validateData} from './guillotine/validateData';

Expand All @@ -35,6 +31,7 @@ export {I18n} from './i18n/i18n';
export {getContentApiUrl} from './utils/getContentApiUrl';
export {getProjectLocaleConfig} from './utils/getProjectLocaleConfig';
export {getProjectLocaleConfigById} from './utils/getProjectLocaleConfigById';
export {getProjectLocaleConfigByLocale} from './utils/getProjectLocaleConfigByLocale';
export {getRequestLocaleInfo} from './utils/getRequestLocaleInfo';
export {sanitizeGraphqlName} from './utils/sanitizeGraphqlName';

Expand Down
5 changes: 5 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export {fetchContent} from './guillotine/fetchContent';
export {fetchContentPathsForAllLocales} from './guillotine/fetchContentPathsForAllLocales';
export {fetchContentPathsForLocale} from './guillotine/fetchContentPathsForLocale';
export {fetchFromApi} from './guillotine/fetchFromApi';
export {fetchGuillotine} from './guillotine/fetchGuillotine';
24 changes: 9 additions & 15 deletions test/guillotine/fetchContent.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import type {
Component,
Context,
GuillotineResponseJson,
RecursivePartial,
} from '../../src/types';
import type {Component, Context, GuillotineResponseJson, RecursivePartial,} from '../../src/types';


import {
Expand All @@ -24,7 +19,6 @@ import {
XP_BASE_URL_HEADER,
XP_REQUEST_TYPE,
} from '../../src/common/constants';
import {ENONIC_APP_NAME} from '../constants';
// import {ws} from '../testUtils';


Expand Down Expand Up @@ -379,7 +373,7 @@ describe('guillotine', () => {
contentJson: GUILLOTINE_RESULT_CONTENT,
metaJson: GUILLOTINE_RESULT_META_MINIMAL,
});
import('../../src').then((moduleName) => {
import('../../src/server').then((moduleName) => {
const context: Context = {
headers: {
get(name: string) {
Expand Down Expand Up @@ -506,7 +500,7 @@ describe('guillotine', () => {
}
},
});
import('../../src').then(async ({fetchContent}) => {
import('../../src/server').then(async ({fetchContent}) => {
const context: Context = {
contentPath: '_/component/path',
};
Expand Down Expand Up @@ -540,7 +534,7 @@ describe('guillotine', () => {
contentJson: GUILLOTINE_RESULT_WITH_ERROR, // Throws before this is used
metaJson: GUILLOTINE_RESULT_WITH_ERROR,
});
import('../../src').then(async ({fetchContent}) => {
import('../../src/server').then(async ({fetchContent}) => {
const context: Context = {
contentPath: '_/component/path',
};
Expand Down Expand Up @@ -574,7 +568,7 @@ describe('guillotine', () => {
contentJson: GUILLOTINE_RESULT_WITH_ERROR, // Throws before this is used
metaJson: GUILLOTINE_RESULT_META_INCOMPLETE,
});
import('../../src').then(async ({fetchContent}) => {
import('../../src/server').then(async ({fetchContent}) => {
const context: Context = {
contentPath: '_/component/path',
};
Expand Down Expand Up @@ -619,7 +613,7 @@ describe('guillotine', () => {

},
});
import('../../src').then(async ({fetchContent}) => {
import('../../src/server').then(async ({fetchContent}) => {
const context: Context = {
contentPath: '_/component/path',
headers: {
Expand Down Expand Up @@ -679,7 +673,7 @@ describe('guillotine', () => {
}
}
}`;
import('../../src').then(async ({ComponentRegistry, fetchContent}) => {
Promise.all([import('../../src'), import('../../src/server')]).then(async ([{ComponentRegistry}, {fetchContent}]) => {
ComponentRegistry.setCommonQuery(QUERY_COMMON);
ComponentRegistry.addContentType(CATCH_ALL, {
configQuery: '{catchAll contentType configQuery}',
Expand Down Expand Up @@ -760,7 +754,7 @@ describe('guillotine', () => {
metaJson: GUILLOTINE_RESULT_META,
});
const BASE_URL = '/base/url';
import('../../src').then((moduleName) => {
import('../../src/server').then((moduleName) => {
const context: Context = {
headers: {
get(name: string) {
Expand Down Expand Up @@ -806,4 +800,4 @@ describe('guillotine', () => {
}); // it

}); // describe fetchContent
}); // describe guillotine
}); // describe guillotine
4 changes: 2 additions & 2 deletions test/guillotine/fetchContentPathsForAllLocales.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ describe('guillotine', () => {
describe('fetchContentPathsForAllLocales', () => {
it('works with just path', () => {
const path = '/HAS_NO_EFFECT_SINCE_RESPONSE_IS_MOCKED';
import('../../src').then((moduleName) => {
import('../../src/server').then((moduleName) => {
expect(moduleName.fetchContentPathsForAllLocales(path))
.resolves.toEqual([{
"contentPath": [""],
Expand Down Expand Up @@ -142,7 +142,7 @@ describe('guillotine', () => {
}`;
const path = '/HAS_NO_EFFECT_SINCE_RESPONSE_IS_MOCKED';
const countPerLocale = 1;
import('../../src').then((moduleName) => {
import('../../src/server').then((moduleName) => {
expect(moduleName.fetchContentPathsForAllLocales(
path, query, countPerLocale
)).resolves.toEqual([{
Expand Down
22 changes: 6 additions & 16 deletions test/guillotine/fetchFromApi.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
import type {
ContentApiBaseBody,
Context,
ProjectLocaleConfig
} from '../../src/types';
import type {ContentApiBaseBody, ProjectLocaleConfig} from '../../src/types';

import {
beforeEach,
describe,
expect,
jest,
test as it
} from '@jest/globals';
import { afterEach } from 'node:test';
import {beforeEach, describe, expect, jest, test as it} from '@jest/globals';
import {afterEach} from 'node:test';


globalThis.console = {
Expand Down Expand Up @@ -98,7 +88,7 @@ describe('guillotine', () => {

describe('fetchFromApi', () => {
it('returns query results', () => {
import('../../src').then((moduleName) => {
import('../../src/server').then((moduleName) => {
moduleName.fetchFromApi(...FETCH_FROM_API_PARAMS_VALID).then((result) => {
// console.debug(result);
expect(result).toEqual({
Expand All @@ -118,12 +108,12 @@ describe('guillotine', () => {
jest.spyOn(globalThis, 'fetch').mockImplementation(() => {
throw new Error('fetch error');
});
import('../../src').then((moduleName) => {
import('../../src/server').then((moduleName) => {
expect(() => moduleName.fetchFromApi(...FETCH_FROM_API_PARAMS_VALID)).rejects.toThrow(Error(JSON.stringify({
code: 'API',
message: 'fetch error'
})));
});
});
}); // fetchFromApi
});
});
Loading