npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@travetto/model-mongo

v4.0.7

Published

Mongo backing for the travetto model module.

Downloads

386

Readme

MongoDB Model Support

Mongo backing for the travetto model module.

Install: @travetto/model-mongo

npm install @travetto/model-mongo

# or

yarn add @travetto/model-mongo

This module provides an mongodb-based implementation for the Data Modeling Support. This source allows the Data Modeling Support module to read, write and query against mongodb.. Given the dynamic nature of mongodb, during development when models are modified, nothing needs to be done to adapt to the latest schema.

Supported features:

Code: Wiring up a custom Model Source

import { InjectableFactory } from '@travetto/di';
import { MongoModelService, MongoModelConfig } from '@travetto/model-mongo';

export class Init {
  @InjectableFactory({
    primary: true
  })
  static getModelSource(conf: MongoModelConfig) {
    return new MongoModelService(conf);
  }
}

where the MongoModelConfig is defined by:

Code: Structure of MongoModelConfig

import type mongo from 'mongodb';

import { RuntimeResources, Env, TimeSpan } from '@travetto/base';
import { Config } from '@travetto/config';
import { Field } from '@travetto/schema';

/**
 * Mongo model config
 */
@Config('model.mongo')
export class MongoModelConfig {
  /**
   * Hosts
   */
  hosts?: string[];
  /**
   * Collection prefix
   */
  namespace?: string;
  /**
   * Username
   */
  username?: string;
  /**
   * Password
   */
  password?: string;
  /**
   * Server port
   */
  port?: number;
  /**
   * Direct mongo connection options
   */
  connectionOptions = {};
  /**
   * Is using the SRV DNS record configuration
   */
  srvRecord?: boolean;

  /**
   * Mongo client options
   */
  @Field(Object)
  options: mongo.MongoClientOptions = {};

  /**
   * Should we auto create the db
   */
  autoCreate?: boolean;

  /**
   * Frequency of culling for cullable content
   */
  cullRate?: number | TimeSpan;

  /**
   * Connection string
   */
  connectionString?: string;

  /**
   * Load all the ssl certs as needed
   */
  async postConstruct(): Promise<void> {
    const resolve = (file: string): Promise<string> => RuntimeResources.resolve(file).then(v => v, () => file);

    if (this.connectionString) {
      const details = new URL(this.connectionString);
      this.hosts ??= details.hostname.split(',').filter(x => !!x);
      this.srvRecord ??= details.protocol === 'mongodb+srv:';
      this.namespace ??= details.pathname.replace('/', '');
      Object.assign(this.options, Object.fromEntries(details.searchParams.entries()));
      this.port ??= +details.port;
      this.username ??= details.username;
      this.password ??= details.password;
    }

    // Defaults
    if (!this.namespace) {
      this.namespace = 'app';
    }
    if (!this.port || Number.isNaN(this.port)) {
      this.port = 27017;
    }
    if (!this.hosts || !this.hosts.length) {
      this.hosts = ['localhost'];
    }

    const opts = this.options;
    if (opts.ssl) {
      if (opts.cert) {
        opts.cert = await Promise.all([opts.cert].flat(2).map(f => Buffer.isBuffer(f) ? f : resolve(f)));
      }
      if (opts.tlsCertificateKeyFile) {
        opts.tlsCertificateKeyFile = await resolve(opts.tlsCertificateKeyFile);
      }
      if (opts.tlsCAFile) {
        opts.tlsCAFile = await resolve(opts.tlsCAFile);
      }
      if (opts.tlsCRLFile) {
        opts.tlsCRLFile = await resolve(opts.tlsCRLFile);
      }
    }

    if (!Env.production) {
      opts.waitQueueTimeoutMS ??= 1000 * 60 * 60 * 24; // Wait a day in dev mode
    }
  }

  /**
   * Build connection URLs
   */
  get url(): string {
    const hosts = this.hosts!
      .map(h => (this.srvRecord || h.includes(':')) ? h : `${h}:${this.port ?? 27017}`)
      .join(',');
    const opts = Object.entries(this.options).map(([k, v]) => `${k}=${v}`).join('&');
    let creds = '';
    if (this.username) {
      creds = `${[this.username, this.password].filter(x => !!x).join(':')}@`;
    }
    const url = `mongodb${this.srvRecord ? '+srv' : ''}://${creds}${hosts}/${this.namespace}?${opts}`;
    return url;
  }
}

Additionally, you can see that the class is registered with the @Config annotation, and so these values can be overridden using the standard Configuration resolution paths.The SSL file options in clientOptions will automatically be resolved to files when given a path. This path can be a ResourceLoader path or just a standard file path.