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

goobs-database-plugin

v0.2.2

Published

A flexible and extensible multi-database plugin for TypeScript projects, initially featuring MongoDB support. This plugin offers generic CRUD operations with company and user segregation, type-safe document handling, automatic metadata tracking, and built

Downloads

421

Readme

goobs-database-plugin

A flexible and extensible multi-database plugin for managing generic document operations with TypeScript support. Currently featuring MongoDB integration, with plans to support additional databases in the future.

Installation

To install the plugin, run:

npm install goobs-database-plugin

or

yarn add goobs-database-plugin

Configuration

  1. Create a .env file in your project root with the following content:
MONGODB_URI=your_mongodb_connection_string_here
  1. Make sure to include the .env file in your .gitignore to keep your credentials secure.

Usage (MongoDB)

First, import the necessary functions and types from the plugin:

import {
  getFromMongo,
  removeFromMongo,
  updateItemInMongo,
  createGenericSchema,
  GenericDocument,
  GenericSerializableData,
} from 'goobs-database-plugin'

Defining a Schema

Create a schema for your document using createGenericSchema:

import { Schema } from 'mongoose'

interface MyDocument {
  name: string
  age: number
}

const mySchema = createGenericSchema<MyDocument>({
  name: { type: String, required: true },
  age: { type: Number, required: true },
})

Retrieving Data

Use getFromMongo to retrieve data:

async function fetchData(companyId: string, userId: string) {
  const result = await getFromMongo<
    MyDocument,
    GenericSerializableData<MyDocument>
  >(companyId, userId, 'MyModel', {
    filter: { age: { $gte: 18 } },
    // Optional: provide cached data and a function to get updatedAt
    cachedData: previouslyFetchedData,
    getUpdatedAt: item => new Date(item.updatedAt),
  })

  console.log(result.data)
  console.log('Is data stale?', result.isStale)
}

Updating Data

Use updateItemInMongo to update or insert data:

async function updateData(
  companyId: string,
  userId: string,
  itemData: Partial<MyDocument> & { _id?: string }
) {
  const updatedItem = await updateItemInMongo<
    MyDocument,
    GenericSerializableData<MyDocument>
  >(companyId, userId, 'MyModel', mySchema, itemData, data => {
    // Validate required fields
    if (!data.name || !data.age) {
      throw new Error('Name and age are required')
    }
  })

  console.log('Updated item:', updatedItem)
}

Removing Data

Use removeFromMongo to delete data:

async function removeData(companyId: string, userId: string, itemId: string) {
  const isRemoved = await removeFromMongo<MyDocument>(
    companyId,
    userId,
    itemId,
    'MyModel',
    mySchema
  )

  console.log('Item removed:', isRemoved)
}

API Reference (MongoDB)

getFromMongo<T, S>

Retrieves data from MongoDB.

  • companyId: string
  • userId: string
  • mongoModelName: string
  • options:
    • itemId?: string
    • filter?: Record<string, unknown>
    • cachedData?: GenericSerializableData[]
    • getUpdatedAt?: (item: GenericSerializableData) => Date

Returns: Promise<{ data: GenericSerializableData<S>[] | GenericSerializableData<S> | null, isStale: boolean }>

updateItemInMongo<T, S>

Updates or inserts a document in MongoDB.

  • companyId: string
  • userId: string
  • mongoModelName: string
  • schema: Schema
  • itemData: Partial & { _id?: string }
  • validateFields: (data: Partial) => void

Returns: Promise<GenericSerializableData<S>>

removeFromMongo<T>

Removes a document from MongoDB.

  • companyId: string
  • userId: string
  • identifier: string
  • mongoModelName: string
  • schema: Schema<GenericDocument>
  • additionalFilter?: Record<string, unknown>

Returns: Promise<boolean>

createGenericSchema<T>

Creates a Mongoose schema with additional fields for company, user, and metadata.

  • schemaFields: Record<keyof T, SchemaDefinitionProperty>

Returns: Schema<GenericDocument<T>>

Types

  • BaseDocument: Extends Mongoose's Document with additional fields.
  • BaseSerializableData: Serializable version of BaseDocument.
  • WithCompanyAndUser: Interface for documents with company and user fields.
  • GenericDocument<T>: Combines a custom type T with BaseDocument and WithCompanyAndUser.
  • GenericSerializableData<T>: Serializable version of GenericDocument<T>.

Error Handling

The plugin uses Winston for logging. Check the log files (generic-get.log, generic-update.log, generic-remove.log, db-connection.log) for detailed error information.

Future Database Support

While this plugin currently supports MongoDB, it is designed with extensibility in mind. Future versions will include support for additional databases, allowing for seamless integration with various database systems.

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests.

License

This project is licensed under the MIT License - see the LICENSE.md file for details.