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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@knorcedger/backend-utils

v2.5.2

Published

A collection of useful utils to use in your backend code

Readme

Backend Utils

A comprehensive collection of utilities designed to simplify backend GraphQL and MongoDB development.

IMPORTANT

This package assumes that you use node 22.6 or newer that supports type stripping

Contents

Installation

npm install @knorcedger/backend-utils

GraphQL Utilities

1. MongoDB to GraphQL Type Conversion

Automatically generate GraphQL types from your Mongoose models.

transformModelToGraphQLTypes()

Transforms a Mongoose model into GraphQL object and enum types.

import UserModel from './models/UserModel';
import { transformModelToGraphQLTypes } from '@knorcedger/backend-utils';

// Generate GraphQL types from your Mongoose model
export const { objectTypes, enumTypes } =
  transformModelToGraphQLTypes(UserModel);

// Access the generated type
export const UserType = objectTypes.UserType;

Use options.omitFields to specify which model fields will be ignored.

const { enumTypes, objectTypes } = transformModelToGraphQLTypes(
  MessageRuleModel,
  { omitFields: ['time'] }
);

createInputTypeFromOutputType()

Converts an output GraphQL type to an input type for mutations.

import GuestAppPreferencesModel from './models/GuestAppPreferencesModel';
import {
  createInputTypeFromOutputType,
  transformModelToGraphQLTypes,
} from '@knorcedger/backend-utils';

// Generate GraphQL types from your model
export const { objectTypes } = transformModelToGraphQLTypes(
  GuestAppPreferencesModel
);

// Get the output type
export const GuestAppPreferencesType = objectTypes.GuestAppPreferencesType;

// Create an input type from the output type
export const {
  inputFields: GuestAppPreferencesInputFields,
  inputType: GuestAppPreferencesInputType,
} = createInputTypeFromOutputType(GuestAppPreferencesType);

2. Make a field of input fields required

// Make email required in the input field
makeInputFieldRequired(ClientInputFields, 'email');

3. Add a new field to an output type

addFieldToType({
  field: {
    description: 'The client _id',
    name: '_id', // Field name
    // resolve: (source, args, context, info) => {
    //   return `Test value for client ID: ${source?._id ?? "unknown"}`;
    // },
    type: GraphQLObjectID, // Field type
    // args: {} // Define arguments here if needed
  },
  type: ClientType, // The GraphQLObjectType to modify
});

4. Remove a field from an output type

removeFieldFromType({
  fieldName: 'password', // the field to remove
  type: ClientType, // The GraphQLObjectType to modify
});

5. GraphQL Type Creation

createTypes()

Creates a set of GraphQL types (output, input, and update) from field definitions.

import { createTypes, GraphQLString } from '@knorcedger/backend-utils';

const userTypes = createTypes('User', {
  email: {
    description: "The user's email address",
    required: ['input', 'output'],
    type: GraphQLString,
  },
  name: {
    description: "The user's full name",
    type: GraphQLString,
  },
  password: {
    description: "The user's password (hashed)",
    include: ['input'],
    required: ['input'],
    type: GraphQLString,
  },
});

// Access the generated types
const { UserType, UserInputType, UserUpdateType } = userTypes;
Field Configuration Properties

Each field can be configured with the following properties:

  • type: The GraphQL type for this field (used when the same type applies to all variants).

    type: GraphQLString;
  • distinctTypes: Define different types for input/output/update (used instead of type).

    distinctTypes: {
      input: GraphQLInputFileType,
      output: GraphQLFileType,
      update: GraphQLInputFileType
    }
  • description: Optional field description that appears in GraphQL documentation.

    description: "The user's profile picture";
  • include: Specifies which type variants should include this field (defaults to all).

    include: ['input', 'output']; // Exclude from update type
  • required: Specifies in which type variants this field is required.

    required: ['input']; // Field is required in input type but optional elsewhere
  • resolve: Custom resolver function for the field (only applied to output type).

    resolve: (user, args, context) => {
      return user.firstName + ' ' + user.lastName;
    };
  • permission: Permission check for accessing field values.

    • 'self': Only the user can access their own data
    • 'loggedin': Any authenticated user can access the field
    permission: 'self'; // Only the user can see their own email

The function returns an object with six properties:

  • [Name]Type: The output GraphQL object type
  • [Name]OutputFields: The fields object for the output type
  • [Name]InputType: The input GraphQL object type for creating new objects
  • [Name]InputFields: The fields object for the input type
  • [Name]UpdateType: The input GraphQL object type for updating objects
  • [Name]UpdateFields: The fields object for the update type

6. Custom GraphQL Scalars

IntRangeType(min, max)

Creates a GraphQL scalar that validates integers within a specified range.

import { IntRangeType } from '@knorcedger/backend-utils';
import { GraphQLObjectType, GraphQLSchema } from 'graphql';

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    fields: {
      rating: { type: IntRangeType(1, 5) }, // Only accepts integers 1-5
    },
    name: 'Query',
  }),
});

7. getRequestedFields

Extracts requested field names from a GraphQL resolver info object.

import { getRequestedFields } from '@knorcedger/backend-utils';

const resolvers = {
  Query: {
    getUser: (_, args, context, info) => {
      const fields = getRequestedFields(info);
      console.log('Requested fields:', fields); // ['id', 'name', 'email', etc.]
      // Now you can optimize your database query based on requested fields
    },
  },
};

8. populate

Intelligently populates MongoDB references based on GraphQL query fields

This function:

  1. Analyzes the GraphQL query to determine which fields were requested
  2. Only populates references for fields that were actually requested
  3. Maintains both the ID reference and the populated object
  4. Works with both single objects and arrays of results
  5. Handles special cases like newly created documents
import { populate } from '@knorcedger/backend-utils';

const resolvers = {
  Query: {
    getPost: async (_, { id }, context, info) => {
      const query = PostModel.findById(id);
      return populate(query, info, ['author', 'comments']);
    },
  },
};

Utility Functions

1. catchAppErrors

catchAppErrors()

Prevents application crashes by catching uncaught exceptions and unhandled promise rejections.

import { catchAppErrors } from '@knorcedger/backend-utils';

// Add this at the end of your main application file
catchAppErrors();

2. optionallyAddAttrs

Selectively copies properties from a source object based on a list of attribute names.

import { optionallyAddAttrs } from '@knorcedger/backend-utils';

const resolvers = {
  Mutation: {
    updateUser: async (_, { id, input }) => {
      // Only update fields that were actually provided
      const updates = optionallyAddAttrs(input, ['name', 'email', 'age']);
      return UserModel.findByIdAndUpdate(id, updates, { new: true });
    },
  },
};

Mongoose Utilities

1. Database Connection

mongooseConnect()

Connects to a MongoDB database using Mongoose with proper error handling.

import mongoose from 'mongoose';
import { mongooseConnect } from '@knorcedger/backend-utils';

// With default logging
await mongooseConnect(mongoose, 'mongodb://localhost:27017/mydatabase');

// With disabled logging
await mongooseConnect(mongoose, 'mongodb://localhost:27017/mydatabase', {
  logging: false,
});

Typescript

Inside the typescript folder there's a tsconfig.json that can be used to run typescript checks in the parent project.

Inside your package.json

"scripts": {
  "typecheck": "cp node_modules/@knorcedger/backend-utils/tsconfig.json . && npx tsc --noEmit && rm -f tsconfig.json"
}

License

ISC

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.