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

add pg-loader #2

Open
sibelius opened this issue Jun 28, 2019 · 1 comment
Open

add pg-loader #2

sibelius opened this issue Jun 28, 2019 · 1 comment

Comments

@sibelius
Copy link
Member

sibelius commented Jun 28, 2019

/**
 * Postgresql Loader use dataloader to batch sql queries
 * @flow
 */
import type { TableSinglePrimaryKey } from '../../TypeDefinition';

function indexResults(results, indexField, cacheKeyFn = key => key) {
  const indexedResults = new Map();
  results.forEach(res => {
    indexedResults.set(cacheKeyFn(res[indexField]), res);
  });
  return indexedResults;
}

function normalizeResults(keys, indexField, cacheKeyFn = key => key) {
  return results => {
    const indexedResults = indexResults(results, indexField, cacheKeyFn);
    return keys.map(val => indexedResults.get(cacheKeyFn(val)) || null);
    //new Error(`Key not found : ${val}`));
  };
}

const pgLoader = async (client: Object, table: TableSinglePrimaryKey, ids: Array<string>, key?: string) => {
  const _key = key || table.primaryKey;
  const where = ids.map(id => `'${id}'`).join(' , ');
  const sql = `select ${Object.keys(table.fields).join(', ')} from ${table.tableName} where ${_key} in (${where})`;

  // console.log('pg loader sql: ', sql);
  // const TAG = `${table.tableName}-${Math.random()}`;
  // console.time(TAG);
  try {
    const result = await client.query(sql, []);
    // console.timeEnd(TAG);

    const { rows } = result;

    // order rows by ids
    return normalizeResults(ids, _key, id => id.toString())(rows);
  } catch (err) {
    console.log('ERROR:POSTGRESQL:', err);
    return normalizeResults(ids, _key, id => id.toString())([]);
  }
};

export default pgLoader;
@sibelius
Copy link
Member Author

usage

export const getLoader = (context: GraphQLContext) =>
  new DataLoader(async ids => pgLoader(context['TableName'], tTable, ids), {
    maxBatchSize: 500,
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant