Skip to content

Instantly share code, notes, and snippets.

@emrul
Created May 11, 2020 21:53
Show Gist options
  • Save emrul/9f53e44de1e7823a01cd01b96d868ae5 to your computer and use it in GitHub Desktop.
Save emrul/9f53e44de1e7823a01cd01b96d868ae5 to your computer and use it in GitHub Desktop.
Attempt at creating graphile plugin
const myOwnEscapeFn = (sql, sqlFragment, type) => {
const actualType = type.domainBaseType || type;
if (actualType.category === "N") {
if (actualType.id === 20) {
return sql.fragment `to_b64_extid(${sqlFragment})`;
}
if (["21" /* int2 */,
"23" /* int4 */,
"700" /* float4 */,
"701" /* float8 */
].includes(actualType.id)) {
// No need for special handling
return sqlFragment;
} // Otherwise force the id to be a string
return sql.fragment `((${sqlFragment})::numeric)::text`;
}
return sqlFragment;
};
exports.TestPlugin = function TestPlugin(builder) {
builder.hook("GraphQLObjectType:fields", function (fieldConfig, build, context) {
const { pgIntrospectionResultsByKind, // From PgIntrospectionPlugin
pgRegisterGqlTypeByTypeId, // From PgTypesPlugin
pgRegisterGqlInputTypeByTypeId, // From PgTypesPlugin
pg2GqlMapper, // From PgTypesPlugin
sql: sql, // From PgBasicsPlugin, this is equivalent to `require('pg-sql2')` but avoids multiple-module conflicts
graphql, } = build;
const addDataGeneratorForField = context.addDataGeneratorForField;
pgIntrospectionResultsByKind.class.forEach(table => {
const tablePgType = table.type;
addDataGeneratorForField("id", () => {
return {
pgQuery: queryBuilder => {
queryBuilder.selectIdentifiers2 = function (table) {
if (this.selectedIdentifiers)
return;
const primaryKey = table.primaryKeyConstraint;
if (!primaryKey)
return;
const primaryKeys = primaryKey.keyAttributes;
this.select(sql.fragment `json_build_array(${sql.join(primaryKeys.map(key => myOwnEscapeFn(sql, sql.fragment `${this.getTableAlias()}.${sql.identifier(key.name)}`, key.type)), ", ")})`, "__identifiers");
this.selectedIdentifiers = true;
};
queryBuilder.selectIdentifiers2(table);
}
};
});
});
return fieldConfig;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment