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

enable ts strict in query package #2457

Merged
merged 6 commits into from
Jun 18, 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: 3 additions & 0 deletions packages/query/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
- enable ts strict mode

## [2.12.1] - 2024-06-12
### Changed
- Update `@subql/utils`
Expand Down
4 changes: 2 additions & 2 deletions packages/query/src/configure/configure.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ async function ensurePool(poolConfig: PoolConfig): Promise<Pool> {
const pgPool = new Pool(poolConfig);
try {
await pgPool.connect();
} catch (e) {
} catch (e: any) {
if (JSON.stringify(e.message).includes(CONNECTION_SSL_ERROR_REGEX)) {
poolConfig.ssl = undefined;
return ensurePool(poolConfig);
Expand Down Expand Up @@ -49,7 +49,7 @@ export class ConfigureModule {
}

return sslConfig;
} catch (e) {
} catch (e: any) {
getLogger('db config').error(e);
throw e;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/query/src/configure/x-postgraphile/debugClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export function debugPgClient(pgClient: PoolClient, logger: Pino.Logger): PoolCl
});
}
}
pgClient._explainResults.forEach(({query, values}: {query: string; values?: any[]}) => {
pgClient._explainResults?.forEach(({query, values}: {query: string; values?: any[]}) => {
let res: string;
res = `\n SQL query: ${query} `;
if (values && values.length !== 0) {
Expand Down
50 changes: 34 additions & 16 deletions packages/query/src/graphql/graphql.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors
// SPDX-License-Identifier: GPL-3.0

import assert from 'assert';
import PgPubSub from '@graphile/pg-pubsub';
import {Module, OnModuleDestroy, OnModuleInit} from '@nestjs/common';
import {HttpAdapterHost} from '@nestjs/core';
import {delay, getDbType, SUPPORT_DB} from '@subql/common';
import {hashName} from '@subql/utils';
import {getPostGraphileBuilder, PostGraphileCoreOptions} from '@subql/x-postgraphile-core';
import {getPostGraphileBuilder, Plugin, PostGraphileCoreOptions} from '@subql/x-postgraphile-core';
import {
ApolloServerPluginCacheControl,
ApolloServerPluginLandingPageDisabled,
Expand Down Expand Up @@ -37,27 +38,43 @@ const logger = getLogger('graphql-module');

const SCHEMA_RETRY_INTERVAL = 10; //seconds
const SCHEMA_RETRY_NUMBER = 5;

class NoInitError extends Error {
constructor() {
super('GraphqlModule has not been initialized');
}
}
@Module({
providers: [ProjectService],
})
export class GraphqlModule implements OnModuleInit, OnModuleDestroy {
private apolloServer: ApolloServer;
private dbType: SUPPORT_DB;
private _apolloServer?: ApolloServer;
private _dbType?: SUPPORT_DB;
constructor(
private readonly httpAdapterHost: HttpAdapterHost,
private readonly config: Config,
private readonly pgPool: Pool,
private readonly projectService: ProjectService
) {}

private get apolloServer(): ApolloServer {
assert(this._apolloServer, new NoInitError());
return this._apolloServer;
}

private get dbType(): SUPPORT_DB {
assert(this._dbType, new NoInitError());
return this._dbType;
}

async onModuleInit(): Promise<void> {
if (!this.httpAdapterHost) {
return;
}
this.dbType = await getDbType(this.pgPool);
this._dbType = await getDbType(this.pgPool);
try {
this.apolloServer = await this.createServer();
} catch (e) {
this._apolloServer = await this.createServer();
} catch (e: any) {
throw new Error(`create apollo server failed, ${e.message}`);
}
if (this.dbType === SUPPORT_DB.cockRoach) {
Expand All @@ -71,15 +88,13 @@ export class GraphqlModule implements OnModuleInit, OnModuleDestroy {
// In order to apply hotSchema Reload without using apollo Gateway, must access the private method, hence the need to use set()
try {
const schema = await this.buildSchema(dbSchema, options);
// @ts-ignore
if (schema && !!this.apolloServer?.generateSchemaDerivedData) {
// @ts-ignore
const schemaDerivedData = await this.apolloServer.generateSchemaDerivedData(schema);
if (schema && !!(this.apolloServer as any)?.generateSchemaDerivedData) {
const schemaDerivedData = await (this.apolloServer as any).generateSchemaDerivedData(schema);
set(this.apolloServer, 'schema', schema);
set(this.apolloServer, 'state.schemaManager.schemaDerivedData', schemaDerivedData);
logger.info('Schema updated');
}
} catch (e) {
} catch (e: any) {
logger.error(e, `Failed to hot reload Schema`);
process.exit(1);
}
Expand All @@ -100,7 +115,7 @@ export class GraphqlModule implements OnModuleInit, OnModuleDestroy {

const graphqlSchema = builder.buildSchema();
return graphqlSchema;
} catch (e) {
} catch (e: any) {
await delay(SCHEMA_RETRY_INTERVAL);
if (retries === 1) {
logger.error(e);
Expand Down Expand Up @@ -133,9 +148,12 @@ export class GraphqlModule implements OnModuleInit, OnModuleDestroy {
const pluginHook = makePluginHook([PgPubSub]);
// Must be called manually to init PgPubSub since we're using Apollo Server and not postgraphile
options = pluginHook('postgraphile:options', options, {pgPool: this.pgPool});
options.replaceAllPlugins.push(PgSubscriptionPlugin);
options.replaceAllPlugins ??= [];
options.appendPlugins ??= [];
options.replaceAllPlugins.push(PgSubscriptionPlugin as Plugin);
while (options.appendPlugins.length) {
options.replaceAllPlugins.push(options.appendPlugins.pop());
const replaceAllPlugin = options.appendPlugins.pop();
if (replaceAllPlugin) options.replaceAllPlugins.push(replaceAllPlugin);
}
}

Expand Down Expand Up @@ -202,7 +220,7 @@ export class GraphqlModule implements OnModuleInit, OnModuleDestroy {
}
}
function limitBatchedQueries(req: Request, res: Response, next: NextFunction): void {
const errors = [];
const errors: UserInputError[] = [];
if (argv['query-batch-limit'] && argv['query-batch-limit'] > 0) {
if (req.method === 'POST') {
try {
Expand All @@ -211,7 +229,7 @@ function limitBatchedQueries(req: Request, res: Response, next: NextFunction): v
errors.push(new UserInputError('Batch query limit exceeded'));
throw errors;
}
} catch (error) {
} catch (error: any) {
res.status(500).json({errors: [...error]});
return next(error);
}
Expand Down
4 changes: 2 additions & 2 deletions packages/query/src/graphql/graphql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ describe('GraphqlModule', () => {
};

const results = await server.executeOperation({query: GET_META});
const fetchedMeta = results.data._metadata;
const fetchedMeta = results.data?._metadata;

expect(fetchedMeta).toMatchObject(mock);
});
Expand Down Expand Up @@ -172,7 +172,7 @@ describe('GraphqlModule', () => {
};

const results = await server.executeOperation({query: GET_META});
const fetchedMeta = results.data._metadata;
const fetchedMeta = results.data?._metadata;

expect(fetchedMeta).toMatchObject(mock);
});
Expand Down
6 changes: 3 additions & 3 deletions packages/query/src/graphql/limit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ describe('query limits', () => {

const server = await createApolloServer();
const results = await server.executeOperation({query: LARGE_UNBOUND_QUERY});
expect(results.data.tables.nodes.length).toEqual(100);
expect(results.data?.tables.nodes.length).toEqual(100);
}, 5000000);

it('bounded unsafe query clamped to safe bound', async () => {
Expand All @@ -105,7 +105,7 @@ describe('query limits', () => {

const server = await createApolloServer();
const results = await server.executeOperation({query: LARGE_BOUNDED_QUERY});
expect(results.data.tables.nodes.length).toEqual(100);
expect(results.data?.tables.nodes.length).toEqual(100);
});

it('bounded safe query remains unchanged', async () => {
Expand All @@ -122,7 +122,7 @@ describe('query limits', () => {

const server = await createApolloServer();
const results = await server.executeOperation({query: LARGE_BOUNDED_QUERY});
expect(results.data.tables.nodes.length).toEqual(50);
expect(results.data?.tables.nodes.length).toEqual(50);
});
});
});
7 changes: 4 additions & 3 deletions packages/query/src/graphql/plugins/GetMetadataPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,15 @@ async function fetchFromApi(): Promise<void> {
meta = await fetch(new URL(`meta`, indexerUrl));
const result = await meta.json();
Object.assign(metaCache, result);
} catch (e) {
} catch (e: any) {
metaCache.indexerHealthy = false;
console.warn(`Failed to fetch indexer meta, `, e.message);
}

try {
health = await fetch(new URL(`health`, indexerUrl));
metaCache.indexerHealthy = !!health.ok;
} catch (e) {
} catch (e: any) {
metaCache.indexerHealthy = false;
console.warn(`Failed to fetch indexer health, `, e.message);
}
Expand Down Expand Up @@ -181,6 +181,7 @@ function findNodePath(nodes: readonly SelectionNode[], path: string[]): FieldNod

if (!newPath.length) return found;

if (!found.selectionSet) return;
return findNodePath(found.selectionSet.selections, newPath);
}
}
Expand Down Expand Up @@ -246,7 +247,7 @@ export const GetMetadataPlugin = makeExtendSchemaPlugin((build: Build, options)
`,
resolvers: {
Query: {
_metadata: async (_parentObject, args, context, info): Promise<MetaData> => {
_metadata: async (_parentObject, args, context, info): Promise<MetaData | undefined> => {
const tableExists = metadataTableSearch(build);
if (tableExists) {
let rowCountFound = false;
Expand Down
7 changes: 4 additions & 3 deletions packages/query/src/graphql/plugins/PgOrderByUnique.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {PgClass} from '@subql/x-graphile-build-pg';
import {Plugin} from 'graphile-build';
import {GraphQLEnumType} from 'graphql';
import isString from 'lodash/isString';
import * as PgSql from 'pg-sql2';
import {argv} from '../../yargs';

const PgConnectionArgOrderBy: Plugin = (builder, {orderByNullsLast}) => {
Expand Down Expand Up @@ -106,7 +107,7 @@ const PgConnectionArgOrderBy: Plugin = (builder, {orderByNullsLast}) => {

const cursorPrefixFromOrderBy = (orderBy: any) => {
if (orderBy) {
const cursorPrefixes = [];
const cursorPrefixes: PgSql.SQLNode[] = [];

for (let itemIndex = 0, itemCount = orderBy.length; itemIndex < itemCount; itemIndex++) {
const item = orderBy[itemIndex];
Expand Down Expand Up @@ -144,8 +145,8 @@ const PgConnectionArgOrderBy: Plugin = (builder, {orderByNullsLast}) => {
specNullsFirst !== null
? specNullsFirst
: orderByNullsLast !== null
? !orderByNullsLast
: undefined;
? !orderByNullsLast
: undefined;
queryBuilder.orderBy(expr, ascending, nullsFirst);
});

Expand Down
2 changes: 1 addition & 1 deletion packages/query/src/graphql/plugins/PgSearchPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const PgSearchPlugin: Plugin = (builder) => {
...field,
resolve(source, args, ctx, info) {
if (args.search !== undefined) {
args.search = parser.parse(args.search).toString();
args.search = parser.parse(args.search)?.toString();
}
return field.resolve?.(source, args, ctx, info);
},
Expand Down
2 changes: 1 addition & 1 deletion packages/query/src/utils/asyncInterval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

//improve util method from : https://dev.to/jsmccrumb/asynchronous-setinterval-4j69

const asyncIntervals = [];
const asyncIntervals: {run: boolean; id: number | NodeJS.Timeout}[] = [];

const runAsyncInterval = async (cb, interval, intervalIndex) => {
await cb();
Expand Down
2 changes: 1 addition & 1 deletion packages/query/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"tsBuildInfoFile": "dist/.tsbuildinfo",
"rootDir": "src",
"outDir": "./dist",
"lib": ["dom"]
"strict": true
},
"references": [{"path": "../common"}, {"path": "../types"}, {"path": "../utils"}],
"include": ["src/**/*"]
Expand Down
Loading