How to use @cardstack/di - 10 common examples

To help you get started, we’ve selected a few @cardstack/di 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 cardstack / cardstack / packages / hub / indexers.js View on Github external
async _doUpdate(forceRefresh, hints) {
      log.debug('begin update, forceRefresh=%s', forceRefresh);
      let priorCache = this._schemaCache;
      let running = new RunningIndexers(
        await this._seedSchema(),
        this.client,
        this.emit.bind(this),
        this.schemaLoader.ownTypes(),
        getOwner(this)
      );
      try {
        let newSchema = await running.update(forceRefresh, hints);
        if (this._schemaCache === priorCache) {
          // nobody else has done a more recent update of the schema
          // cache than us, so we can try to update it.
          if (priorCache) {
            let oldSchema = await priorCache;
            if (!newSchema.equalTo(oldSchema)) {
              log.info('schema was changed');
              this._schemaCache = newSchema;
              if (oldSchema) {
                await oldSchema.teardown();
              }
            }
          } else {
github cardstack / cardstack / packages / hub / main.js View on Github external
);

  if (typeof opts.seeds === 'function') {
    registry.register('config:initial-models', opts.seeds);
  } else {
    registry.register('config:initial-models', () => []);
  }

  if (process.env.PROFILE_MEMORY_SEC) {
    setInterval(
      () => writeSnapshot((err, filename) => log.info(`heap dump written to ${filename}`)),
      process.env.PROFILE_MEMORY_SEC * 1000
    );
  }

  let container = new Container(registry);

  // in the test suite we want more deterministic control of when
  // indexing happens
  if (!opts.disableAutomaticIndexing) {
    await container.lookup(`plugin-client:${require.resolve('@cardstack/pgsearch/client')}`).ensureDatabaseSetup();
    startIndexing(opts.environment, container); // dont await boot-time indexing, invalidation logic has our back
  }

  // this registration pattern is how we make broccoli wait for our
  // asynchronous startup stuff before running the first build.
  if (opts.broccoliConnector) {
    opts.broccoliConnector.setSource(container.lookup('hub:code-generators'));
  }

  return container;
}
github cardstack / cardstack / packages / ephemeral / searcher.js View on Github external
const { declareInjections } = require('@cardstack/di');

module.exports = declareInjections(
  {
    service: `plugin-services:${require.resolve('./service')}`,
  },

  class EphemeralSearcher {
    static create(...args) {
      return new this(...args);
    }
    constructor({ dataSource, service, config }) {
      this.config = config;
      this.dataSource = dataSource;
      this.service = service;
    }

    async get(session, type, id, next) {
      return next();
github cardstack / cardstack / packages / ethereum / cardstack / writer.js View on Github external
const crypto = require('crypto');
const Error = require('@cardstack/plugin-utils/error');
const PendingChange = require('@cardstack/plugin-utils/pending-change');
const { declareInjections } = require('@cardstack/di');
const Session = require('@cardstack/plugin-utils/session');
const { merge, get } = require('lodash');

const pendingChanges = new WeakMap();
const proxiedTypes = ['tracked-ethereum-addresses', 'user-ethereum-addresses'];

module.exports = declareInjections({
  indexers: 'hub:indexers',
  controllingBranch: 'hub:controlling-branch',
  writers: 'hub:writers',
  searchers: 'hub:searchers',
  transactionIndexer: `plugin-services:${require.resolve('./transaction-indexer')}`
}, class EthereumWriter {

  async prepareCreate(branch, session, type, document) {
    if (type === 'user-ethereum-addresses') {
      let { data: existingUserAddress } = await this.searchers.searchFromControllingBranch(Session.INTERNAL_PRIVILEGED, {
        filter: {
          type: { exact: type },
          'address-user.id': { exact: session.id },
          'address-user.type': { exact: session.type },
        }
      });
github cardstack / cardstack / packages / hub / sessions.js View on Github external
const { declareInjections } = require('@cardstack/di');
const Session = require('@cardstack/plugin-utils/session');

module.exports = declareInjections(
  {
    searcher: 'hub:searchers',
  },

  class Sessions {
    constructor() {
      this._userSearcher = null;
    }

    get userSearcher() {
      if (!this._userSearcher) {
        this._userSearcher = {
          get: (type, userId) => {
            return this.searcher.get(Session.INTERNAL_PRIVILEGED, 'local-hub', type, userId);
          },
          search: params => {
github cardstack / portfolio / cards / asset-history / cardstack / history-indexer.js View on Github external
const { declareInjections } = require('@cardstack/di');
const { get, sortBy, uniqBy } = require('lodash');
const { utils: { BN } } = require('web3');
const moment = require('moment-timezone');
const Session = require('@cardstack/plugin-utils/session');
const log = require('@cardstack/logger')('portfolio/asset-history/history-indexer');
const { updateBalanceFromTransaction } = require('portfolio-utils');
const DEFAULT_MAX_ASSET_HISTORIES = 1000000;

let indexJobNumber = 0;

module.exports = declareInjections({
  searchers: 'hub:searchers',
  schema: 'hub:current-schema',
  pgsearchClient: `plugin-client:${require.resolve('@cardstack/pgsearch/client')}`,
  transactionIndex: `plugin-client:${require.resolve('@cardstack/ethereum/cardstack/transaction-index')}`,
},

  class HistoryIndexer {
    static create(...args) {
      return new this(...args);
    }

    constructor({ pgsearchClient, schema, searchers, transactionIndex }) {
      this.searchers = searchers;
      this.schema = schema;
      this.pgsearchClient = pgsearchClient;
      this.transactionIndex = transactionIndex;
github cardstack / cardstack / packages / hub / data-sources.js View on Github external
const { declareInjections } = require('@cardstack/di');

module.exports = declareInjections(
  {
    currentSchema: 'hub:current-schema',
  },

  class DataSources {
    async active() {
      let schema = await this.currentSchema.getSchema();
      return schema.getDataSources();
    }
  }
);
github cardstack / cardstack / packages / sftp / cardstack / searcher.js View on Github external
const { declareInjections }   = require('@cardstack/di');
const SftpClient = require('ssh2-sftp-client');
const { dirname, basename } = require('path');
const moment = require('moment');
const { lookup } = require('mime-types');

module.exports = declareInjections({
  currentSchema: 'hub:current-schema'
},

class SftpSearcher {
  static create(...args) {
    return new this(...args);
  }
  constructor({ dataSource, config, currentSchema, connection }) {
    this.config        = config;
    this.dataSource    = dataSource;
    this.connection    = connection;
    this.currentSchema = currentSchema;
  }

  async get(session, type, id, next) {
github cardstack / cardstack / packages / hub / indexers / static-models.js View on Github external
/*
  This indexers is responsible for reflecting all our initial static
  models (which includes the bootstrap schema plus the user's
  hard-coded data-sources) in the search index.
*/

const { declareInjections } = require('@cardstack/di');
const { isEqual } = require('lodash');
const bootstrapSchema = require('../bootstrap-schema');

module.exports = declareInjections(
  {
    dataSources: 'config:data-sources',
    schemaLoader: 'hub:schema-loader',
  },

  class StaticModelsIndexer {
    static create({ dataSources, schemaLoader }) {
      let models = bootstrapSchema.concat(dataSources);
      let schemaTypes = schemaLoader.ownTypes();
      let schemaModels = models.filter(m => schemaTypes.includes(m.type));
      return new this(models, schemaModels);
    }

    constructor(models, schemaModels) {
      this.models = models;
      this.schemaModels = schemaModels;
github cardstack / cardstack / packages / hub / queues.js View on Github external
const Queue = require('@cardstack/queue');
const { declareInjections } = require('@cardstack/di');
const log = require('@cardstack/logger')('cardstack/queue');

module.exports = declareInjections(
  {
    config: 'config:pg-boss',
  },
  class Queues {
    static create({ config }) {
      log.debug('Creating new queue instance');
      return new Queue(config);
    }

    static async teardown(instance) {
      log.debug('Tearing down queue instance');
      await instance.stop();
    }
  }
);

@cardstack/di

dependency injection support for cardstack hub

MIT
Latest version published 11 months ago

Package Health Score

68 / 100
Full package analysis

Similar packages