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/platform-callbacks

v0.8.0

Published

RxStack platform specific middleware

Downloads

61

Readme

RxStack Platform Callbacks

Node.js CI Maintainability Test Coverage

Set of helpers for @rxstack/platform

Table of content

Installation

npm install @rxstack/platform-callbacks --save

Callbacks

Note: preExecute applies changes on request.body and postExecute on event.getData()

alter

Pick or pluck properties in data

Available on:

  • preExecute
  • postExecute

Options:

Example:

// ...
import {alter} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    alter('pick', ['name', 'user.fname'])
  ],
  onPreExecute: [
    // ...
    alter('omit', ['_id', 'name'])
  ]
})

rename

Rename property and removes the original one.

Available on:

  • preExecute
  • postExecute

Options:

  • key: property name to rename
  • newKey: new property name
  • dataPath: path to data (optional)

Example:

// ...
import {rename} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    rename('title', 'name')
  ],
  onPreExecute: [
    // ...
    rename('_id', 'id', 'user')
  ]
})

associateWithCurrentUser

Adds current user identifier to request.body.

Available on:

  • preExecute

Options:

  • options: CurrentUserOptions
    • idField: user identifier property. Optional, defaults to id
    • targetField: property where user identifier should be set. Optional, defaults to userId

Example:

// ...
import {associateWithCurrentUser} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    associateWithCurrentUser({idField: 'username', targetField: 'owner'})
  ]
})

queryWithCurrentUser

Adds current user identifier to request.attributes.get('query') or request.attributes.get('criteria').

Available on:

  • preExecute

Options:

  • options: CurrentUserOptions
    • idField: user identifier property. Optional, defaults to id
    • targetField: property where user identifier should be set. Optional, defaults to userId

Example:

// ...
import {queryWithCurrentUser} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    queryWithCurrentUser({idField: 'username', targetField: 'owner'})
  ]
})

restrictToAuthenticatedUser

Restricts resource to authenticated user request.token.

Available on:

  • preExecute

Options:

  • fullyAuthenticated: if user is fully authenticated (token is not refreshed) (optional)

Example:

// ...
import {restrictToAuthenticatedUser} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    restrictToAuthenticatedUser(false)
  ]
})

restrictToAnonymousUser

Restricts resource to anonymous user request.token.

Available on:

  • preExecute

Example:

// ...
import {restrictToAnonymousUser} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    restrictToAnonymousUser()
  ]
})

restrictToOwner

Restricts resource to current user request.token.getUser().

Available on:

  • preExecute

Options:

  • options: CurrentUserOptions
    • idField: user identifier property. Optional, defaults to id
    • targetField: property where user identifier should be get. Optional, defaults to userId

Example:

// ...
import {restrictToOwner} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    restrictToOwner({idField: 'username', targetField: 'owner'})
  ]
})

restrictToRole

Restricts resource to current user role request.token.getRoles().

Available on:

  • preExecute

Options:

  • role: role to match

Example:

// ...
import {restrictToRole} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    restrictToRole('ROLE_ADMIN')
  ]
})

objectExists

Checks if object exists in database.

Available on:

  • preExecute

Options:

  • schema: ObjectExistSchema<T>
    • service: The type of service to fetch the record
    • targetField: field in the request.body
    • inverseField: field in the service model
    • method: service method (optional), defaults to findOne
    • criteria: additional criteria (optional) see here
    • dataPath: path to data (optional)

Example:

// ...
import {objectExists} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    objectExists({
      service: UserService,
      targetField: 'user',
      inverseField: 'username',
      method: 'findOne',
      criteria: {id: {'$ne': 'user-2'}},
      dataPath: 'posts'
    })
  ]
})

populate

Joins related records.

Available on:

  • postExecute

Options:

  • schema: PopulateSchema<T>
    • service: The type of service to fetch the records
    • targetField: field in the event.getData()
    • inverseField: field in the service model
    • method: service method (optional), defaults to findMany
    • nameAs: replaces the original property name (optional)
    • query: additional query (optional) see here

Example:

// ...
import {populate} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPostExecute: [
    // ...
    populate({
      service: UserService,
      targetField: 'users',
      inverseField: 'username',
      method: 'findMany',
      query: {where: {enabled: {'$eq': true}}, limit: 5, skip: 0, sort: { id: -1 } },
      nameAs: 'owners'
    })
  ]
})

queryFilter

Filter the query with @rxstack/query-filter. Modifies request.attributes.get('query').

Available on:

  • preExecute

Options:

  • schema: QueryFilterSchema

Example:

// ...
import {queryFilter} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    queryFilter(taskQuerySchema)
  ]
})

setNow

Set the current date-time in certain fields

Available on:

  • preExecute
  • postExecute

Options:

  • fieldNames: array of field names.

Example:

// ...
import {setNow} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    setNow('createdAt', 'updatedAt')
  ]
})

softDelete

Flag records as logically deleted instead of physically removing them (sets the deleted date). It can be used only with ResurceOperations Internally it modifies the request.attributes.get(query) or checks if deleteField is null

Important: make sure you add it last on remove operations because it will skip the remaining hooks.

Available on:

  • preExecute

Options:

  • schema: SoftDeleteOptions
    • addOnCreate: Adds delete field with null value on create operations (optional), defaults to false
    • deleteField: name of the field to set the date when the record was logically deleted (optional), defaults to deletedAt

Example:

// ...
import {softDelete} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    softDelete({
      addOnCreate: true,
      deleteField: 'deletedAt'
    })
  ]
})

transform

Transforms values from request.body or event.getData(). It uses class-transformer

Available on:

  • preExecute
  • postExecute

Options:

Example:

first create the model:

import {Expose} from 'class-transformer';

export class TaskTransformer {

  @Expose({name: 'id'})
  _id: string;

  @Expose({groups: ['create']})
  name: string;
}

then add the hook to operation:

// ...
import {transform} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    transform(TaskTransformer, {groups: ['create']})
  ]
})

validate

Validates object(s) using class-validator

Available on:

  • preExecute

Options:

  • type: validation schema or target which types are being specified.
  • options: ValidatorOptions (optional)

Example with type:

// ...
import {validate} from '@rxstack/platform-callbacks';
import {IsBoolean, IsNotEmpty, Length} from 'class-validator';

export class TaskModel {

  @IsNotEmpty({
    groups: ['group1']
  })
  id: string;

  @Length(2, 20, {
    groups: ['group2']
  })
  name: string;

  @IsBoolean({
    groups: ['group1']
  })
  completed: boolean;
}

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    validate(TaskModel, { groups: ['group1'] })
  ]
})

validateUnique

Validates that a particular field (or fields) is (are) unique.

Available on:

  • preExecute

Options:

  • service: The type of service to fetch the records
  • properties: List of fields on which this object should be unique
  • errorPath: the path where the error should be mapped
  • method: service method (optional), defaults to findMany
  • message: error message (optional), default to Value is not unique

Example:

// ...
import {validateUnique} from '@rxstack/platform-callbacks';

@Operation<ResourceOperationMetadata<Task>>({
  // ...
  onPreExecute: [
    // ...
    validateUnique({
      service: TaskService,
      properties: ['name'],
      errorPath: 'name',
      method: 'findMany',
      message: 'Property name should be unique'
    })
  ]
})

License

Licensed under the MIT license.