Skip to content

Commit

Permalink
Split exports to client/server/common #474
Browse files Browse the repository at this point in the history
  • Loading branch information
pmi committed Feb 8, 2024
1 parent a210d5b commit b1123de
Show file tree
Hide file tree
Showing 9 changed files with 44 additions and 46 deletions.
3 changes: 2 additions & 1 deletion .gitignore
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
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
@@ -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 !!!
/** 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 '${key}' is missing (from .env?)`);
}
});

6 changes: 3 additions & 3 deletions src/guillotine/fetchContent.ts
@@ -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
@@ -1,19 +1,14 @@
import type {
ContentApiBaseBody,
GuillotineResponse,
GuillotineResponseJson,
ProjectLocaleConfig,
} from '../types';
import type {ContentApiBaseBody, GuillotineResponse, GuillotineResponseJson, ProjectLocaleConfig,} from '../types';

Check failure on line 1 in src/guillotine/fetchFromApi.ts

View workflow job for this annotation

GitHub Actions / test & lint

Unexpected trailing comma


/** 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
@@ -1,20 +1,16 @@
import type {
ContentApiBaseBody,
GuillotineResult,
ProjectLocaleConfig,
} from '../types';
import type {ContentApiBaseBody, GuillotineResult, ProjectLocaleConfig,} from '../types';

Check failure on line 1 in src/guillotine/fetchGuillotine.ts

View workflow job for this annotation

GitHub Actions / test & lint

Unexpected trailing comma


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
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
@@ -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';
14 changes: 8 additions & 6 deletions tsconfig.json
Expand Up @@ -7,7 +7,7 @@
// dom and dom.iterable for now.
"dom",
"dom.iterable",
"esnext",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
Expand All @@ -23,7 +23,7 @@

"outDir": ".",
"declaration": true,
"sourceMap": true,
"sourceMap": true

// We have done Triple-Slash Directives where needed instead:
// "types": [
Expand All @@ -36,15 +36,17 @@
// Specifies an allowlist of files to include in the program. An error occurs
// if any of the files can’t be found.
"files": [
"src/index.ts"
"src/index.ts",
"src/client.ts",
"src/server.ts",
"src/baseMappings.ts"
],

// Specifies an array of filenames or patterns to include in the program.
// These filenames are resolved relative to the directory containing the
// tsconfig.json file.
"include": [
"src/**/*.ts",
"src/**/*.tsx"
"src/views/**/*.ts*"
],

// Specifies an array of filenames or patterns that should be skipped when
Expand All @@ -61,5 +63,5 @@
"moduleTypes": {
"jest.config.ts": "cjs"
}
},
}
}

0 comments on commit b1123de

Please sign in to comment.