Skip to main content
Version: 0.6.0 (Latest)

🔧 Common Validator Blocks

Common validator blocks provide generic validation functions that can be used across different domains in Nodeblocks applications. These validators ensure proper parameter validation, authentication, and access control for any type of resource.


🎯 Overview

Common validator blocks are designed to:

  • Provide generic validation functions for reuse across domains
  • Ensure proper authentication and authorization for any resource
  • Validate common parameter types (UUIDs, numbers, required fields)
  • Support flexible access control with role-based and self-access patterns
  • Handle cross-cutting concerns in a consistent way

📋 Common Validator Types

Authentication Validators

Validators that check authentication and authorization for any resource.

Parameter Validators

Validators that check parameter format and presence.


🔧 Available Common Validators

some

Composes validators with OR semantics. Passes if any validator passes.

Purpose: Combine multiple validators where only one needs to succeed

Parameters:

  • ...args: Validator[] - Array of validators to compose with OR logic

Returns: Validator - A new validator function that passes if any input validator passes

Throws:

  • NodeblocksError (500) with message "Unknown error" if a validator throws a non-NodeblocksError
  • Throws the first NodeblocksError from failed validators if all validators fail

Usage:

import { validators } from '@nodeblocks/backend-sdk';

const { some, hasOrgRole, ownsOrder } = validators;

withRoute({
-- snip --
validators: [
some(
hasOrgRole(['admin'], ['requestParams', 'organizationId']),
ownsOrder(['requestParams', 'orderId'])
)
]
});

checkIdentityType

Checks if the authenticated user's identity type matches allowed types.

Purpose: Gate access based on identity type configuration

Parameters:

  • allowedTypes: tuple of allowed identity type keys (e.g. ['admin', 'moderator'])

Returns: void - Passes through if identity type is allowed

Throws:

  • NodeblocksError (500) with message "db.identities is not set"
  • NodeblocksError (500) with message "configuration.identity.typeIds is not set"
  • NodeblocksError (401) with message "Invalid token"
  • NodeblocksError (403) with message "Failed to fetch identity"
  • NodeblocksError (403) with message "Invalid identity type ID"
  • NodeblocksError (403) with message "Identity is not authorized to access this resource"

Usage:

import { validators } from '@nodeblocks/backend-sdk';

const { checkIdentityType } = validators;

withRoute({
-- snip --
validators: [
checkIdentityType(['admin', 'moderator'])
]
});

Important: Legacy parameter validators

The following validators use a legacy interface and will be deprecated and removed later:

  • requireParam
  • isUUID
  • isNumber

They do not accept the standard RouteHandlerPayload. Instead, extract payload.params.requestParams and pass it manually:

({ params: { requestParams } }) => requireParam('identityId')(requestParams)
({ params: { requestParams } }) => isUUID('identityId')(requestParams)
({ params: { requestParams } }) => isNumber('limit')(requestParams)

As a result, these legacy validators cannot be composed directly with helpers like compose() or some(). Prefer standard validators or custom validators following the normal payload signature for composition.

validateResourceAccess

Validates resource access based on allowed subjects and token type.

Deprecated

This validator is deprecated.
Replacement: isSelf for checking self access, checkIdentityType for use of identity types.

Purpose: Generic access control validator for any resource type

Parameters:

  • allowedSubjects: string[] - Array of allowed user types/subjects
  • authenticate: Authenticator - Authentication function (optional, defaults to getBearerTokenInfo)
  • payload: RouteHandlerPayload - Contains request context and data

Returns: void - Passes through if user has appropriate permissions

Throws:

  • NodeblocksError (401) with message "App token is not valid" or "User token is not valid"
  • NodeblocksError (500) with message "Failed to find identity"
  • NodeblocksError (401) with message "Identity not found"
  • NodeblocksError (403) with message "Identity is not authorized to access this resource"
  • NodeblocksError (401) with message "Token does not have a valid access type"

Supported Subjects:

  • 'self' - User can access their own resources (ID-based matching)
  • 'admin' - Administrator access (typeId: '100')
  • 'user' - Regular user access (typeId: '001')
  • 'guest' - Guest access (typeId: '000')

Identity ID Sources (for self-access, checked in order):

  • payload.context.data.identityId
  • payload.params.requestParams.identityId
  • payload.params.requestQuery.identityId
  • payload.params.requestBody.identityId

Identity Type Configuration (defaults):

{
admin: '100',
guest: '000',
user: '001'
}

Access Logic:

  • App tokens: Always pass if appId is valid
  • User tokens:
    • For 'self' subject: Match identity ID with resource identity ID
    • For role subjects: Match identity typeId with configured typeId
    • At least one subject must match for access to be granted

Usage:

import { validators } from '@nodeblocks/backend-sdk';

const { validateResourceAccess } = validators;

withRoute({
-- snip --
validators: [validateResourceAccess(['admin'])]
});
withRoute({
-- snip --
validators: [validateResourceAccess(['self', 'admin'])]
});
withRoute({
-- snip --
validators: [validateResourceAccess(['admin', 'user', 'guest'])]
});

requireParam

Creates a validator that ensures a required parameter is present and not null.

Purpose: Factory function to create parameter requirement validators

Parameters:

  • key: string - The parameter name to validate

Returns: Validator - Validator function that checks for parameter presence

Throws: Error with message "Missing required parameter: [parameterName]"

Usage:

import { validators } from '@nodeblocks/backend-sdk';

const { requireParam } = validators;

withRoute({
-- snip --
validators: [({params: { requestParams }}) => requireParam('identityId')(requestParams)]
});

isUUID

Creates a validator that ensures a parameter follows valid UUID v4 format.

Purpose: Factory function to create UUID format validators

Parameters:

  • key: string - The parameter name to validate as UUID

Returns: Validator - Validator function that checks UUID format

Throws: Error with message "Invalid UUID format for parameter: [parameterName]"

UUID Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx (where x is hexadecimal and y is 8, 9, a, or b)

Usage:

import { validators } from '@nodeblocks/backend-sdk';

const { isUUID } = validators;

withRoute({
-- snip --
validators: [({params: { requestParams }}) => isUUID('categoryId')(requestParams)]
});

isNumber

Creates a validator that ensures a parameter can be converted to a valid number.

Purpose: Factory function to create numeric format validators

Parameters:

  • key: string - The parameter name to validate as numeric

Returns: Validator - Validator function that checks numeric conversion

Throws: Error with message "Parameter [parameterName] must be a number"

Usage:

import { validators } from '@nodeblocks/backend-sdk';

const { isNumber } = validators;

withRoute({
-- snip --
validators: [({params: { requestParams }}) => isNumber('categoryNum')(requestParams)]
});

ownsResource

Checks if the authenticated user is the owner of a resource in the database.

Purpose: Generic ownership validator powering specialized ownership validators

Parameters:

  • resource: one of 'chatChannels' | 'chatMessages' | 'orders' | 'users' | 'subscriptions'
  • ownerIdPathInResource: tuple path to owner field in the resource (e.g. ['identityId'])
  • resourceIdPathInPayload: tuple path to the resource ID in payload

Returns: void - Passes through if the authenticated identity owns the resource

Throws:

  • NodeblocksError (401) with message "Invalid token"
  • NodeblocksError (500) with message "Resource does not exist"
  • NodeblocksError (400) with message "Invalid resource ID"
  • NodeblocksError (403) with message "Failed to fetch resource"
  • NodeblocksError (403) with message "Invalid owner ID"
  • NodeblocksError (403) with message "Identity is not the owner of the resource"

Usage:

import { validators } from '@nodeblocks/backend-sdk';

const { ownsResource } = validators;

withRoute({
-- snip --
validators: [
ownsResource('orders', ['identityId'], ['requestParams', 'orderId'])
]
});