How to use dataloader - 10 common examples

To help you get started, we’ve selected a few dataloader examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github preconstruct / preconstruct / packages / cli / src / prompt.ts View on Github external
export function createPromptConfirmLoader(
  message: string
): (pkg: NamedThing) => Promise {
  let loader = new DataLoader(pkgs =>
    limit(() =>
      (async () => {
        if (pkgs.length === 1) {
          let { confirm } = await enquirer.prompt([
            {
              type: "confirm",
              name: "confirm",
              message,
              // @ts-ignore
              prefix: prefix + " " + pkgs[0].name,
              initial: true
            }
          ]);
          return [confirm];
        }
        let { answers } = await enquirer.prompt([
github okgrow / advanced-graphql / api / src / model / Location.js View on Github external
import NodeGeocoder from 'node-geocoder';
import Dataloader from 'dataloader';

const { GOOGLE_API_KEY } = process.env;

const geocoder = NodeGeocoder({
  provider: 'google',
  apiKey: GOOGLE_API_KEY,
});

// smarter loader!
const loader = new Dataloader(names => {
  // uncomment to debug
  // console.log('running the loader with', names.length, 'names');
  return Promise.all(names.map(name => geocoder.geocode(name)));
});

export default class Location {
  async get(name) {
    if (!name) {
      return;
    }

    try {
      const [location] = await loader.load(name);

      return {
        ...location,
github smartprix / xorm / src / model.js View on Github external
const cache = !!options.ctx;
		const ctx = this._getLoaderCtx(options);

		let loaderName = `${this.tableName}${columnName}DataLoader`;
		if (options.modify) {
			if (_.isPlainObject(options.modify)) {
				loaderName += JSON.stringify(options.modify);
			}
			else {
				loaderName += String(options.modify);
			}
		}

		if (ctx[loaderName]) return ctx[loaderName];

		ctx[loaderName] = new DataLoader(async (keys) => {
			// this is for avoiding un-necessary queries where the value is 0 or null
			const filteredKeys = _.uniq(keys.filter(key => (key && key !== '0')));
			let results = [];
			if (filteredKeys.length) {
				const query = this.query(knex).whereIn(columnName, filteredKeys);
				if (options.modify) {
					if (_.isPlainObject(options.modify)) {
						query.where(options.modify);
					}
					else {
						query.modify(options.modify);
					}
				}
				results = await query;
			}
			return mapManyResults(results, keys, columnName);
github nodkz / conf-talks / articles / graphql / dataloader / dl-schema.js View on Github external
resolve: (source, args, context, info) => {
        // See dl-server.js, there was created context = { dataloaders: new WeakMap() };
        const { dataloaders } = context;
        // init DataLoader once, if not exists
        // we use a MAGIC here
        // `Set.get(info.fieldNodes)` is unique for every field in the query
        // it helps to determine the same resolvers
        let dl = dataloaders.get(info.fieldNodes);
        if (!dl) {
          dl = new DataLoader(async (ids: any) => {
            // regular request to our database
            const rows = await authorModel.findByIds(ids);
            // IMPORTANT: we MUST return rows in the same order like we get ids
            const sortedInIdsOrder = ids.map(id => rows.find(x => x.id === id));
            return sortedInIdsOrder;
          });
          dataloaders.set(info.fieldNodes, dl);
        }
        // load author via dataloader
        return dl.load(source.authorId);
      },
    },
github tmeasday / create-graphql-server / test / output-app / model / Tweet.js View on Github external
constructor(context) {
    this.context = context;
    this.collection = context.db.collection('tweet');
    this.pubsub = context.pubsub;
    this.loader = new DataLoader(ids => findByIds(this.collection, ids));
  }
github reactioncommerce / reaction / src / core / util / createDataLoaders.js View on Github external
export const dataLoaderFactory = (dlFunc) => new DataLoader(dlFunc, { cache: false });
github cloudflare / workers-graphql-gateway-example / src / graphql.js View on Github external
"https://cloudflare-dns.com/dns-query?name=" + x.name + "&type=" + x.type,
    {
      headers: {
        Accept: "application/dns-json"
      }
    }
  );
  let ans = await req.json();
  return ans.Answer;
}

async function batchResolver(keys) {
  return keys.map(id => resolve(id));
}

self.resolvers = new DataLoader(
  keys => batchResolver(keys),
  q => {
    q.type + q.name;
  }
);

class Root {
  constructor() {}
  async resolve(x) {
    return self.resolvers.load(x);
  }
}

export default async function handleGraphQLRequest(request) {
  let gql = await decodequery(request);
  let response = await graphql(schema, gql.query, new Root());
github okgrow / advanced-graphql / api / src / model / User.js View on Github external
constructor(context) {
    this.context = context;
    this.collection = context.db.collection('user');
    this.loader = new DataLoader(ids => findByIds(this.collection, ids));
  }
github MichalLytek / type-graphql / experiments / prisma / generated / type-graphql / resolvers / relations / User / UserRelationsResolver.ts View on Github external
return function getUserPostsDataLoader(args: any) {
    const argsJSON = JSON.stringify(args);
    let userPostsDataLoader = argsToDataLoaderMap.get(argsJSON);
    if (!userPostsDataLoader) {
      userPostsDataLoader = new DataLoader(async keys => {
        const fetchedData: any[] = await photon.users.findMany({
          where: { id: { in: keys } },
          select: {
            id: true,
            posts: args,
          },
        });
        return keys
          .map(key => fetchedData.find(data => data.id === key)!)
          .map(data => data.posts);
      });
      argsToDataLoaderMap.set(argsJSON, userPostsDataLoader);
    }
    return userPostsDataLoader;
  }
}
github robcrowley / graphql-demo / server / src / data / loaders.js View on Github external
const createLoaders = viewer => {
    const labelLoader = new DataLoader(ids => Label.get(viewer, ids));

    const artistLoader = new DataLoader(ids => Artist.get(viewer, ids));

    const artistWatchLoader = new DataLoader(ids => ArtistWatch.get(viewer, ids));

    const albumReviewLoader = new DataLoader(ids => AlbumReview.get(viewer, ids));

    const albumLoader = new DataLoader(ids => Album.get(viewer, ids));

    const userLoader = new DataLoader(ids =>
        Promise.all(ids.map(id => User
            .get(viewer, id)
            .then(user => {
                if (user) {
                    userByLoginLoader.prime(user.login, user);
                }
                return user;
            }))
        )
    );

    const userByLoginLoader = new DataLoader(logins =>
        Promise.all(logins.map(login => User
            .getByLogin(viewer, login)
            .then(user => {
                if (user) {

dataloader

A data loading utility to reduce requests to a backend via batching and caching.

MIT
Latest version published 2 years ago

Package Health Score

87 / 100
Full package analysis

Popular dataloader functions