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

mongoose-dataloader-generator

v1.0.1

Published

Abstract class that provided properly typed interfaces in order to create Dataloaders in one shot.

Downloads

6

Readme

mongoose-dataloader-generator

Abstract class that provided properly typed interfaces in order to create Dataloaders in one shot.

Takes an array of mongoose models (mongoose.Model)[] and creates dataloaders for each model. *see examples.

Install

npm i mongoose-dataloader-generator

or

yarn add mongoose-dataloader-generator

Example Use

Models and Document Interfaces

//interfaces.ts
import mongoose, { Document, Schema } from 'mongoose'
export interface UserDocument extends Document {
  email: string
  password: string
  name: string
}

export const User = mongoose.model<UserDocument>(
  'User',
  new Schema<UserDocument>({
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: String,
    name: String,
  })
)

export interface SurveyDocument extends Document {
  name: string
  user: UserDocument
  questions: SurveyQuestionDocument[]
}

export const Survey = mongoose.model<SurveyDocument>(
  'Survey',
  new Schema<SurveyDocument>({
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
    },
    name: String,
    questions: [
      { type: mongoose.Schema.Types.ObjectId, ref: 'SurveyQuestion' },
    ],
  })
)

export interface SurveyQuestionDocument extends Document {
  survey: SurveyDocument
  title: string
  options: string[]
  answers: string[]
}
export const SurveyQuestion = mongoose.model<SurveyQuestionDocument>(
  'SurveyQuestion',
  new Schema<SurveyQuestionDocument>({
    survey: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Survey',
    },
    title: String,
    options: [String],
    answers: [String],
  })
)

Example Class (MongooseLoader)

//MongooseLoader.ts
import MongooseLoaderGenerator, {
  LoaderRecorType,
  GenericLoaders,
  GenericModels,
} from 'mongoose-dataloader-generator'
import {
  Survey,
  User,
  SurveyQuestion,
  SurveyDocument,
  UserDocument,
  SurveyQuestionDocument,
} from './interfaces'

// Create a type with the Interfaces you want to support
type DocumentTypes = [SurveyDocument, UserDocument, SurveyQuestionDocument] // You can add as many as you want here.

//Create Loaders, Models and RecordType Using the Generic Helpers
type MyLoaders = GenericLoaders<DocumentTypes>
type Models = GenericModels<DocumentTypes>
interface RecordType extends LoaderRecorType<DocumentTypes> {
  surveyLoader: MyLoaders[0]
  userLoader: MyLoaders[1]
  surveyQuestionLoader: MyLoaders[2]
  //...other here//
}

const MODELS: Models = [Survey, User, SurveyQuestion] //Array descrived by Models type. (add more here if needed)

//Extend the Generator class and pass the models to the constructor.
export class MongooseLoader extends MongooseLoaderGenerator<
  DocumentTypes,
  RecordType
> {
  constructor() {
    super(MODELS)
  }
  //Implement initialize.
  // It should set all the loaders by calling the method `createLoaders`.
  async initialize() {
    const [
      surveyLoader,
      userLoader,
      surveyQuestionLoader,
    ] = this.createLoaders()
    this.loaders.surveyLoader = surveyLoader
    this.loaders.userLoader = userLoader
    this.loaders.surveyQuestionLoader = surveyQuestionLoader
    return this.loaders
  }
}

Express Middleware Example

import express, { Request } from 'express'
import { WIthLoaderRequest } from 'mongoose-dataloader-generator'
import { MongooseLoader } from './MongooseLoader'

const app = express()
const loader = new MongooseLoader()
//by default will attach the loader property to the request.
app.use(loader.expressMiddleware)

// Request properly typed.
export interface MyRequest<
  P = Request['params'],
  ResBody = any,
  ReqBody = any,
  ReqQuery = Request['query']
> extends WIthLoaderRequest<MongooseLoader, P, ResBody, ReqBody, ReqQuery> {}

app.get('/user/:id', async (req: MyRequest<{ id: string }>, res) => {
  const { id } = req.params
  const user = await req.loader!.loaders.userLoader.load(id)
  res.json(user)
})