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

@rxstack/mongoose-service

v0.8.2

Published

RxStack Mongoose Service

Downloads

97

Readme

The RxStack Mongoose Service

Node.js CI Maintainability Test Coverage

Mongoose service that implements @rxstack/platform adapter API and querying syntax.

This adapter also requires a running MongoDB database server.

Table of content

Installation

npm install @rxstack/mongoose-service --save

Setup

MongooseServiceModule needs to be registered in the application. Let's create the application:

import {Application, ApplicationOptions} from '@rxstack/core';
import {MongooseServiceModule} from '@rxstack/mongoose-service';

export const APP_OPTIONS: ApplicationOptions = {
  imports: [
    MongooseServiceModule.configure({
      connection: {
        uri: process.env.MONGO_HOST, // mongodb://localhost:27017/test
        // mongoose options
        options: { }
      },
    })
  ],
  providers: [
    // ...
  ]
};

new Application(APP_OPTIONS).start();

Module Options

  • connection.url: mongodb server uri
  • connection.options: mongoose options (optional)
  • logger.enabled: enable query logging (defaults to false)
  • logger.level: logging level (defaults to debug)

Service Options

In addition to service base options we need to set the following options:

Usage

Create interfaces

First we need to create model interface and InjectionToken:

import {InjectionToken} from 'injection-js';
import {MongooseService} from '@rxstack/mongoose-service';

export interface Product {
  id: string;
  name: string;
}

export const PRODUCT_SERVICE = new InjectionToken<MongooseService<Product>>('PRODUCT_SERVICE');

Create mongoose schemas

import { Schema } from 'mongoose';
const { v4: uuid } = require('uuid');

export const productMongooseSchema = new Schema({
  _id: {
    type: String,
    default: uuid
  },
  name: {
    type: String,
    unique: true,
    required: true,
  }
}, {_id: false, versionKey: false });

then register the service in the application provides:

import {ApplicationOptions} from '@rxstack/core';
import {MongooseService} from '@rxstack/mongoose-service';
import {Connection} from 'mongoose';

export const APP_OPTIONS: ApplicationOptions = {
  // ...
  providers: [
    {
      provide: PRODUCT_SERVICE,
      useFactory: (conn: Connection) => {
        return new MongooseService({
          idField: '_id', defaultLimit: 25, model: conn.model('Product', productMongooseSchema)
        });
      },
      deps: [Connection],
    },
  ]
};

How to use in controller

import {Connection} from 'mongoose';
import {Injectable} from 'injection-js';
import {Http, Request, Response, WebSocket, InjectorAwareInterface} from '@rxstack/core';

@Injectable()
export class ProductController implements InjectorAwareInterface {

  @Http('POST', '/product', 'app_product_create')
  @WebSocket('app_product_create')
  async createAction(request: Request): Promise<Response> {
    // getting connection
    const connection = injector.get(Connection);
   
    // standard use
    const service = this.injector.get(PRODUCT_SERVICE);
    await service.insertOne(request.body);
  }
}

Read more about platform services

Commands

Helpful commands managing your mongoose database

Ensure Indexes

Makes the indexes in MongoDB match the indexes defined in this model's schema

npm run cli mongoose:ensure-indexes

Drop databases

Drop databases, collections and indexes for your documents.

npm run cli mongoose:drop

Validation Observer

ValidationObserver converts mongoose errors to BadRequestException.

In order to return proper validation errors and status code 400 we catch the exception and throw BadRequestException. The error messages can be accessed exception.data['errors'] and implement ValidationError[].

License

Licensed under the MIT license.