Skip to content
Merged
3 changes: 2 additions & 1 deletion src/checkpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ export default class Checkpoint {
return {
log: this.log.child({ component: 'resolver' }),
knex: this.knex,
pg: this.pg
pg: this.pg,
computedResolvers: this.opts?.resolvers
};
}

Expand Down
6 changes: 5 additions & 1 deletion src/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
import pluralize from 'pluralize';
import { GqlEntityController } from './graphql/controller';
import { OverridesConfig } from './types';
import { getDerivedFromDirective } from './utils/graphql';
import { getComputedDirective, getDerivedFromDirective } from './utils/graphql';

type TypeInfo = {
type: string;
Expand Down Expand Up @@ -154,6 +154,8 @@ export const codegen = (
: ` constructor(id: ${idType.baseType}, indexerName: string) {\n`;
contents += ` super(${modelName}.tableName, indexerName);\n\n`;
typeFields.forEach(field => {
if (getComputedDirective(field)) return;

const fieldType =
field.type instanceof GraphQLNonNull ? field.type.ofType : field.type;
if (
Expand Down Expand Up @@ -189,6 +191,8 @@ export const codegen = (
contents += ` }\n\n`;

typeFields.forEach(field => {
if (getComputedDirective(field)) return;

const fieldType =
field.type instanceof GraphQLNonNull ? field.type.ofType : field.type;
if (
Expand Down
5 changes: 4 additions & 1 deletion src/graphql/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { OverridesConfig } from '../types';
import { getNestedResolver, queryMulti, querySingle } from './resolvers';
import {
generateQueryForEntity,
getComputedDirective,
getDerivedFromDirective,
getNonNullType,
multiEntityQueryName,
Expand Down Expand Up @@ -168,7 +169,7 @@ export class GqlEntityController {

if (itemType instanceof GraphQLObjectType) {
resolvers[field.name] = getNestedResolver(
multiEntityQueryName(itemType)
singleEntityQueryName(itemType)
);
}
}
Expand Down Expand Up @@ -236,6 +237,8 @@ export class GqlEntityController {
t.specificType('block_range', 'int8range').notNullable();

this.getTypeFields(type).forEach(field => {
if (getComputedDirective(field)) return;

const fieldType =
field.type instanceof GraphQLNonNull
? field.type.ofType
Expand Down
8 changes: 7 additions & 1 deletion src/graphql/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
getTableName,
QueryFilter
} from '../utils/database';
import { getComputedConfigs } from '../utils/graphql';

/**
* Creates getLoader function that will return existing, or create a new dataloader
Expand All @@ -33,10 +34,15 @@ export const createGetLoader = (context: ResolverContextInput) => {
const tableName = getTableName(name);

let query = context.knex
.select('*')
.select(`${tableName}.*`)
.from(tableName)
.whereIn(field, ids as string[]);

const computed = getComputedConfigs(context.computedResolvers, name);
for (const [fieldName, config] of Object.entries(computed)) {
query = query.select(config.sql(context.knex).as(fieldName));
}

query = applyQueryFilter(query, tableName, filter);
query = applyDefaultOrder(query, tableName);

Expand Down
71 changes: 66 additions & 5 deletions src/graphql/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,18 @@ import {
} from 'graphql-parse-resolve-info';
import { Knex } from 'knex';
import { Pool as PgPool } from 'pg';
import { ComputedResolvers } from '../types';
import {
applyDefaultOrder,
applyQueryFilter,
getTableName,
QueryFilter
} from '../utils/database';
import { getDerivedFromDirective, getNonNullType } from '../utils/graphql';
import {
getComputedConfigs,
getDerivedFromDirective,
getNonNullType
} from '../utils/graphql';
import { Logger } from '../utils/logger';

type BaseArgs = {
Expand Down Expand Up @@ -54,6 +59,7 @@ export type ResolverContextInput = {
log: Logger;
knex: Knex;
pg: PgPool;
computedResolvers?: ComputedResolvers;
};

export type ResolverContext = ResolverContextInput & {
Expand Down Expand Up @@ -82,6 +88,15 @@ export async function queryMulti(
const nestedEntitiesMappings = {} as Record<string, Record<string, string>>;

let query = knex.select(`${tableName}.*`).from(tableName);

const entityComputedResolvers = getComputedConfigs(
context.computedResolvers,
returnType.name
);
for (const [fieldName, config] of Object.entries(entityComputedResolvers)) {
query = query.select(config.sql(knex).as(fieldName));
}

query = applyQueryFilter(query, tableName, {
block: args.block,
indexer: args.indexer
Expand All @@ -97,9 +112,54 @@ export async function queryMulti(
return isListType(fieldType);
};

const cmpOps: Record<string, string> = {
'': '=',
_not: '!=',
_gt: '>',
_gte: '>=',
_lt: '<',
_lte: '<='
};
const likeOps: Record<string, string> = {
_contains: 'like',
_not_contains: 'not like',
_contains_nocase: 'ilike',
_not_contains_nocase: 'not ilike'
};
const applyComputedWhere = (
currentQuery: Knex.QueryBuilder,
sub: Knex.QueryBuilder,
suffix: string,
value: any
): Knex.QueryBuilder | null => {
const expr = knex.raw('(?)', [sub]);
if (suffix in cmpOps)
return currentQuery.where(expr, cmpOps[suffix], value);
if (suffix in likeOps)
return currentQuery.where(expr, likeOps[suffix], `%${value}%`);
if (suffix === '_in') return currentQuery.where(expr, 'in', value);
if (suffix === '_not_in')
return currentQuery.where(expr, 'not in', value);
return null;
};

Object.entries(where).map((w: [string, any]) => {
// TODO: we could generate where as objects { name, column, operator, value }
// so we don't have to cut it there
for (const [name, config] of Object.entries(entityComputedResolvers)) {
Comment thread
Sekhmet marked this conversation as resolved.
Resolved
if (!w[0].startsWith(name)) continue;
const suffix = w[0].slice(name.length);
const applied = applyComputedWhere(
query,
config.sql(knex),
suffix,
w[1]
);
if (applied) {
query = applied;
return;
}
}
Comment thread
Sekhmet marked this conversation as resolved.
Resolved

if (w[0].endsWith('_not')) {
const fieldName = w[0].slice(0, -4);
Expand Down Expand Up @@ -238,8 +298,9 @@ export async function queryMulti(
}

if (args.orderBy) {
const isComputed = args.orderBy in entityComputedResolvers;
query = query.orderBy(
`${tableName}.${args.orderBy}`,
isComputed ? args.orderBy : `${tableName}.${args.orderBy}`,
args.orderDirection?.toLowerCase() || 'desc'
);
}
Expand Down Expand Up @@ -334,7 +395,7 @@ export async function querySingle(
}

export const getNestedResolver =
(columnName: string) =>
(entityName: string) =>
async (
parent: Result,
args: unknown,
Expand Down Expand Up @@ -369,7 +430,7 @@ export const getNestedResolver =
let result: Record<string, any>[] = [];
if (!derivedFromDirective) {
const loaderResult = await getLoader(
columnName,
entityName,
'id',
queryFilter
).loadMany(parent[info.fieldName]);
Expand All @@ -389,7 +450,7 @@ export const getNestedResolver =
}

result = await getLoader(
columnName,
entityName,
fieldArgument.value.value,
queryFilter
).load(parent.id);
Expand Down
15 changes: 15 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Knex } from 'knex';
import pino from 'pino';
import { z } from 'zod';
import { Instance } from './providers';
Expand All @@ -15,6 +16,15 @@ export type TemplateSource = {
template: string;
};

export type ComputedFieldConfig = {
sql: (knex: Knex) => Knex.QueryBuilder;
};

export type ComputedResolvers = Record<
string,
Record<string, ComputedFieldConfig>
>;

export interface CheckpointOptions {
/** Setting this to true will trigger reset of database on config changes. */
resetOnConfigChange?: boolean;
Expand Down Expand Up @@ -42,6 +52,11 @@ export interface CheckpointOptions {
* This can speed up indexing process if you don't need block data.
*/
skipBlockFetching?: boolean;
/**
* Custom resolvers for @computed fields.
* Format: { EntityName: { fieldName: resolverFn } }
*/
resolvers?: ComputedResolvers;
}

export type ContractSourceConfig = z.infer<typeof contractSourceConfigSchema>;
Expand Down
64 changes: 40 additions & 24 deletions src/utils/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,34 +11,36 @@ import {
} from 'graphql';
import { jsonToGraphQLQuery } from 'json-to-graphql-query';
import pluralize from 'pluralize';
import { ComputedResolvers } from '../types';

const directiveDef = (name: string, args: any[] = []) => ({
kind: 'DirectiveDefinition',
name: { kind: 'Name', value: name },
arguments: args,
locations: [{ kind: 'Name', value: 'FIELD_DEFINITION' }]
});

const nonNullStringArg = (name: string) => ({
kind: 'InputValueDefinition',
name: { kind: 'Name', value: name },
type: {
kind: 'NonNullType',
type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } }
}
});

export const extendSchema = (schema: string): string => {
const ast = parse(schema);

const updatedAst = visit(ast, {
Document(node) {
const directiveDefinition = {
kind: 'DirectiveDefinition',
name: { kind: 'Name', value: 'derivedFrom' },
arguments: [
{
kind: 'InputValueDefinition',
name: { kind: 'Name', value: 'field' },
type: {
kind: 'NonNullType',
type: {
kind: 'NamedType',
name: { kind: 'Name', value: 'String' }
}
}
}
],
locations: [{ kind: 'Name', value: 'FIELD_DEFINITION' }]
};

return {
...node,
definitions: [directiveDefinition, ...node.definitions]
definitions: [
directiveDef('derivedFrom', [nonNullStringArg('field')]),
directiveDef('computed'),
...node.definitions
]
};
},
ObjectTypeDefinition(node) {
Expand Down Expand Up @@ -134,7 +136,21 @@ export const getNonNullType = <T>(type: T): T => {
return type;
};

export const getDerivedFromDirective = (field: GraphQLField<any, any>) => {
const directives = field.astNode?.directives ?? [];
return directives.find(dir => dir.name.value === 'derivedFrom');
};
const getDirective = (field: GraphQLField<any, any>, name: string) =>
(field.astNode?.directives ?? []).find(d => d.name.value === name);

export const getDerivedFromDirective = (f: GraphQLField<any, any>) =>
getDirective(f, 'derivedFrom');

export const getComputedDirective = (f: GraphQLField<any, any>) =>
getDirective(f, 'computed');

export const getComputedConfigs = (
resolvers: ComputedResolvers | undefined,
typeName: string
) =>
resolvers
? Object.entries(resolvers).find(
([k]) => k.toLowerCase() === typeName.toLowerCase()
)?.[1] || {}
: {};
Comment thread
Sekhmet marked this conversation as resolved.
Resolved
Loading