Skip to content

Commit

Permalink
Colorful logging
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan committed Jun 21, 2021
1 parent 3670a27 commit d19ae0f
Show file tree
Hide file tree
Showing 17 changed files with 165 additions and 194 deletions.
5 changes: 2 additions & 3 deletions examples/openapi-react-weatherbit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,13 @@
"graphql": "15.4.0"
},
"devDependencies": {
"@graphql-mesh/cli": "0.30.2",
"ts-node": "9.0.0"
"@graphql-mesh/cli": "0.30.2"
},
"scripts": {
"prestart": "yarn build:mesh",
"prebuild": "yarn build:mesh",
"build:mesh": "yarn mesh build --dir=./src/mesh",
"start": "SKIP_PREFLIGHT_CHECK=true react-scripts start",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
Expand Down
2 changes: 0 additions & 2 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,6 @@
"graphql-helix": "1.6.1",
"graphql-upload": "12.0.0",
"graphql-ws": "5.1.2",
"ora": "5.4.1",
"chalk": "4.1.1",
"change-case": "4.1.2",
"js-yaml": "4.1.0",
"json-bigint-patch": "0.0.4",
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/serve/graphql-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export const graphqlHandler = (mesh$: ReturnType<typeof getMesh>): RequestHandle
});
break;
default:
throw new Error(`Unknown GraphQL Result: ${inspect(result)}`);
throw new Error(`Unknown GraphQL Result: ${inspect(result, true, 2, true)}`);
}
})
.catch(e => {
Expand Down
9 changes: 3 additions & 6 deletions packages/cli/src/commands/serve/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import { promises as fsPromises } from 'fs';
import { ProcessedConfig } from '@graphql-mesh/config';
import { getMesh } from '@graphql-mesh/runtime';
import { handleFatalError } from '../../handleFatalError';
import { spinner } from '../../spinner';
import open from 'open';
import { useServer } from 'graphql-ws/lib/use/ws';
import { env } from 'process';
Expand All @@ -34,16 +33,14 @@ interface ServeMeshOptions {
}

export async function serveMesh({ baseDir, argsPort, meshConfig }: ServeMeshOptions) {
spinner.start('Generating Mesh schema...');
meshConfig.logger.info(`Generating Mesh schema...`);
let readyFlag = false;

const mesh$ = getMesh(meshConfig)
.then(mesh => {
readyFlag = true;
if (spinner.isSpinning) {
if (!fork) {
spinner.succeed(`Serving GraphQL Mesh: ${serverUrl}`);
}
if (!fork) {
meshConfig.logger.info(`🕸️ => Serving GraphQL Mesh: ${serverUrl}`);
}
return mesh;
})
Expand Down
113 changes: 52 additions & 61 deletions packages/cli/src/commands/ts-artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import * as tsOperationsPlugin from '@graphql-codegen/typescript-operations';
import * as tsGenericSdkPlugin from '@graphql-codegen/typescript-generic-sdk';
import { isAbsolute, relative, join } from 'path';
import ts from 'typescript';
import { writeFile } from '@graphql-mesh/utils';

const unifiedContextIdentifier = 'MeshContext';

Expand Down Expand Up @@ -49,7 +50,7 @@ function buildSignatureBasedOnRootFields(
args${argsExists ? '' : '?'}: ${argsName};
context: ${unifiedContextIdentifier};
info: GraphQLResolveInfo;
selectionSet?: (subtree: import('graphql').SelectionSetNode) => SelectionSetNode;
selectionSet?: (subtree: SelectionSetNode) => SelectionNode;
}) => Promise<${codegenHelpers.getTypeToUse(parentTypeNode)}['${fieldName}']>`;
}
return operationMap;
Expand Down Expand Up @@ -113,6 +114,7 @@ export async function generateTsArtifacts({
baseDir: string;
rawConfig: YamlConfig.Config;
}) {
const artifactsDir = join(baseDir, '.mesh');
const codegenOutput = await codegen({
filename: 'types.ts',
documents,
Expand All @@ -135,20 +137,16 @@ export async function generateTsArtifacts({
resolvers: tsResolversPlugin,
contextSdk: {
plugin: async () => {
const commonTypes = [`import { MeshContext as BaseMeshContext } from '@graphql-mesh/runtime';`];
const commonTypes = [
`import { MeshContext as BaseMeshContext } from '@graphql-mesh/runtime';`,
`import { SelectionNode, SelectionSetNode } from 'graphql';`,
];
const sdkItems: string[] = [];
const contextItems: string[] = [];
const results = await Promise.all(
rawSources.map(source => {
const sourceMap = unifiedSchema.extensions.sourceMap as Map<RawSourceOutput, GraphQLSchema>;
let sourceSchema = sourceMap.get(source);
if (!sourceSchema) {
for (const [keySource, valueSchema] of sourceMap.entries()) {
if (keySource.name === source.name) {
sourceSchema = valueSchema;
}
}
}
const sourceSchema = sourceMap.get(source);
const item = generateTypesForApi({
schema: sourceSchema,
name: source.name,
Expand All @@ -171,41 +169,7 @@ export async function generateTsArtifacts({
.filter(Boolean)
.join(' & ')} & BaseMeshContext;`;

return {
content: [...commonTypes, ...sdkItems, ...contextItems, contextType].join('\n\n'),
};
},
},
},
plugins: [
{
typescript: {},
},
{
resolvers: {
useIndexSignature: true,
noSchemaStitching: mergerType !== 'stitching',
contextType: unifiedContextIdentifier,
federation: mergerType === 'federation',
},
},
{
contextSdk: {},
},
{
typescriptOperations: {},
},
{
typescriptGenericSdk: {},
},
],
});

const artifactsDir = join(baseDir, '.mesh');

const tsResult = [
codegenOutput,
/* TypeScript */ `
const meshMethods = `
import { processConfig, ConfigProcessOptions } from '@graphql-mesh/config';
import { getMesh } from '@graphql-mesh/runtime';
import { MeshStore, FsStoreStorageAdapter } from '@graphql-mesh/store';
Expand Down Expand Up @@ -263,22 +227,49 @@ export async function getBuiltMesh(configProcessOptions?: ConfigProcessOptions)
export async function getMeshSDK(configProcessOptions?: ConfigProcessOptions) {
const { sdkRequester } = await getBuiltMesh(configProcessOptions);
return getSdk(sdkRequester);
}
`,
].join('\n');
}`;

return {
content: [...commonTypes, ...sdkItems, ...contextItems, contextType, meshMethods].join('\n\n'),
};
},
},
},
plugins: [
{
typescript: {},
},
{
resolvers: {
useIndexSignature: true,
noSchemaStitching: mergerType !== 'stitching',
contextType: unifiedContextIdentifier,
federation: mergerType === 'federation',
},
},
{
contextSdk: {},
},
{
typescriptOperations: {},
},
{
typescriptGenericSdk: {},
},
],
});

const tsFilePath = join(artifactsDir, 'index.ts');
const compilerOptions: ts.CompilerOptions = {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ESNext,
baseUrl: baseDir,
declaration: true,
};
const host = ts.createCompilerHost(compilerOptions);
const oldFileExists = host.fileExists.bind(host);
const oldReadFile = host.readFile.bind(host);
host.fileExists = fileName => (fileName === tsFilePath ? true : oldFileExists(fileName));
host.readFile = fileName => (fileName === tsFilePath ? tsResult : oldReadFile(fileName));
const program = ts.createProgram([tsFilePath], compilerOptions, host);
program.emit();
await writeFile(tsFilePath, codegenOutput);
const jsResult = ts.transpileModule(codegenOutput, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ESNext,
sourceMap: false,
inlineSourceMap: false,
importHelpers: true,
},
});
const jsFilePath = join(artifactsDir, 'index.js');
await writeFile(jsFilePath, jsResult.outputText);
}
24 changes: 12 additions & 12 deletions packages/cli/src/handleFatalError.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import { Logger } from '@graphql-mesh/types';
import { spinner } from './spinner';
import { env, exit } from 'process';
import { inspect } from 'util';

export function handleFatalError(e: Error, logger: Logger): any {
const errorText = e.message;
if (spinner.isSpinning) {
spinner.fail(errorText);
} else {
logger.error(errorText);
}
logger.error(errorText);
if (env.DEBUG) {
logger.error(
inspect({
...e,
name: e.name,
stack: e.stack,
message: e.message,
})
inspect(
{
...e,
name: e.name,
stack: e.stack,
message: e.message,
},
true,
Infinity,
true
)
);
}
exit(1);
Expand Down
17 changes: 8 additions & 9 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { existsSync } from 'fs';
import { FsStoreStorageAdapter, MeshStore } from '@graphql-mesh/store';
import { printSchemaWithDirectives } from '@graphql-tools/utils';
import { writeFile, pathExists, rmdirs } from '@graphql-mesh/utils';
import { spinner } from './spinner';
import { handleFatalError } from './handleFatalError';
import { cwd, env } from 'process';
import yargs from 'yargs';
Expand Down Expand Up @@ -131,7 +130,7 @@ export async function graphqlMesh() {
}
);

spinner.text = 'Reading Mesh configuration';
logger.info(`Reading Mesh configuration`);
const meshConfig = await findAndParseConfig({
dir: baseDir,
ignoreAdditionalResolvers: true,
Expand All @@ -140,7 +139,7 @@ export async function graphqlMesh() {
});
logger = meshConfig.logger;

spinner.text = 'Generating Mesh schema';
logger.info(`Generating Mesh schema`);
const mesh = await getMesh(meshConfig);
destroy = mesh?.destroy;
} catch (e) {
Expand All @@ -160,7 +159,7 @@ export async function graphqlMesh() {
const rootArtifactsName = '.mesh';
const outputDir = join(baseDir, rootArtifactsName);

spinner.start('Cleaning existing artifacts');
logger.info('Cleaning existing artifacts');
await rmdirs(outputDir);

const importedModulesSet = new Set<string>();
Expand All @@ -182,7 +181,7 @@ export async function graphqlMesh() {
}
);

spinner.text = 'Reading Mesh configuration';
logger.info(`Reading Mesh configuration`);
const meshConfig = await findAndParseConfig({
dir: baseDir,
ignoreAdditionalResolvers: true,
Expand All @@ -191,11 +190,11 @@ export async function graphqlMesh() {
});
logger = meshConfig.logger;

spinner.text = 'Generating Mesh schema';
logger.info(`Generating Mesh schema`);
const { schema, destroy, rawSources } = await getMesh(meshConfig);
await writeFile(join(outputDir, 'schema.graphql'), printSchemaWithDirectives(schema));

spinner.text = 'Generating artifacts';
logger.info(`Generating artifacts`);
await generateTsArtifacts({
unifiedSchema: schema,
rawSources,
Expand All @@ -207,9 +206,9 @@ export async function graphqlMesh() {
rawConfig: meshConfig.config,
});

spinner.text = 'Cleanup';
logger.info(`Cleanup`);
destroy();
spinner.succeed('Done! => ' + outputDir);
logger.info('Done! => ' + outputDir);
} catch (e) {
handleFatalError(e, logger);
}
Expand Down
5 changes: 0 additions & 5 deletions packages/cli/src/spinner.ts

This file was deleted.

10 changes: 5 additions & 5 deletions packages/handlers/json-schema/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ export default class JsonSchemaHandler implements MeshHandler {
throw new Error(`Unknown method ${operationConfig.method}`);
}
}
operationLogger.debug(`=> Fetching ${urlObj.toString()}=>${inspect(requestInit, null, 2)}`);
operationLogger.debug(`=> Fetching ${urlObj.toString()}=>${inspect(requestInit, true, 2, true)}`);
const response = await fetch(urlObj.toString(), requestInit);
const responseText = await response.text();
operationLogger.debug(
Expand All @@ -277,7 +277,7 @@ export default class JsonSchemaHandler implements MeshHandler {
} catch (e) {
// The result might be defined as scalar
if (isScalarType(returnType)) {
operationLogger.debug(` => Return type is not a JSON so returning ${inspect(responseText, null, 2)}`);
operationLogger.debug(` => Return type is not a JSON so returning ${responseText}`);
return responseText;
}
throw responseText;
Expand All @@ -301,18 +301,18 @@ export default class JsonSchemaHandler implements MeshHandler {
if (!('getFields' in returnType && 'errors' in returnType.getFields())) {
const aggregatedError = new AggregateError(errors.map(normalizeError));
aggregatedError.stack = null;
this.logger.debug(`=> Throwing the error ${inspect(aggregatedError, null, 2)}`);
this.logger.debug(`=> Throwing the error ${inspect(aggregatedError, true, Infinity, true)}`);
return aggregatedError;
}
}
if (responseJson.error) {
if (!('getFields' in returnType && 'error' in returnType.getFields())) {
const normalizedError = normalizeError(responseJson.error);
operationLogger.debug(`=> Throwing the error ${inspect(normalizedError, null, 2)}`);
operationLogger.debug(`=> Throwing the error ${inspect(normalizedError, true, Infinity, true)}`);
return normalizedError;
}
}
operationLogger.debug(`=> Returning ${inspect(responseJson, null, 2)}`);
operationLogger.debug(`=> Returning ${inspect(responseJson, true, Infinity, true)}`);
return responseJson;
};
}
Expand Down
2 changes: 1 addition & 1 deletion packages/handlers/json-schema/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,7 @@ export function getComposerFromJSONSchema(schema: JSONSchema, logger: Logger): P
const getGenericJSONScalar = (isInput: boolean, description?: string) => {
const coerceValue = (value: any) => {
if (!validate(value)) {
throw new Error(`${inspect(value)} is not valid!`);
throw new Error(`${inspect(value, false, 1, false)} is not valid!`);
}
return value;
};
Expand Down
3 changes: 2 additions & 1 deletion packages/handlers/postgraphile/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ export default class PostGraphileHandler implements MeshHandler {
}

if (!pgPool || !('connect' in pgPool)) {
const pgLogger = this.logger.child('PostgreSQL');
pgPool = new pg.Pool({
connectionString: this.config.connectionString,
log: messages => this.logger.debug(messages),
log: messages => pgLogger.debug(messages),
...this.config?.pool,
});
}
Expand Down
Loading

0 comments on commit d19ae0f

Please sign in to comment.