Skip to content

API Reference Overview

Complete API reference for Nevr. This page provides a comprehensive index of all public exports.

Quick Import Guide

typescript
// Core functionality
import { nevr, entity, action, step } from "nevr"

// Field types
import { string, text, int, float, bool, datetime, json, email } from "nevr"

// Relations
import { belongsTo, hasMany, hasOne, selfRef } from "nevr"

// Pre-built actions
import { softDeleteAction, restoreAction, cloneAction, toggleAction } from "nevr"

// Rules
import { everyone, authenticated, owner, admin, defineRule } from "nevr"

// Errors
import { NevrErrorClass, validationError, notFoundError } from "nevr"

// Plugins
import { createPlugin, endpoint } from "nevr"

// Services (DI)
import { ServiceContainer, createService } from "nevr"

// Workflow
import { workflow, runWorkflow } from "nevr"

// Logger & Utils
import { getLogger, setLogger, capitalize, pascalCase } from "nevr"

// Drivers & Adapters (subpath imports)
import { prisma } from "nevr/drivers/prisma"
import { expressAdapter } from "nevr/adapters/express"

Core Functions

FunctionDescriptionLink
nevr(config)Create Nevr instanceReference
entity(name, fields)Define entityReference
action(name?)Create custom actionReference
step(name, execute, compensate?)Create workflow stepReference
workflow(name)Create workflow definitionReference
ServiceContainer()Create service containerReference
resolveEntity(entity)Resolve entity builder to entityReference

Field Types

TypeTypeScriptDatabaseLink
stringstringVARCHAR(255)Reference
textstringTEXTReference
intnumberINTEGERReference
floatnumberDOUBLEReference
boolean / boolbooleanBOOLEANReference
datetimeDateTIMESTAMPReference
jsonunknownJSON/JSONBReference
jsonTyped<T>()TJSON/JSONBReference
emailstringVARCHAR(255)Reference

See Fields Reference for all methods.


Relations

FunctionDescriptionExample
belongsTo(() => Entity)Many-to-one relationauthor: belongsTo(() => user)
hasMany(() => Entity)One-to-many relationposts: hasMany(() => post)
hasOne(() => Entity)One-to-one relationprofile: hasOne(() => profile)
selfRef()Self-referential relationparent: selfRef().optional()

Pre-built Actions

FunctionEndpointDescription
softDeleteAction(field?)DELETE /:id/softSoft delete with timestamp
restoreAction(field?)POST /:id/restoreRestore soft-deleted record
archiveAction()POST /:id/archiveSet archived = true
unarchiveAction()POST /:id/unarchiveSet archived = false
cloneAction(exclude?)POST /:id/cloneDuplicate record
bulkUpdateAction()PUT /bulkUpdate multiple records
bulkDeleteAction()DELETE /bulkDelete multiple records
toggleAction(field)POST /:id/toggle-{field}Toggle boolean field
exportAction()GET /exportExport as JSON/CSV
countAction()GET /countCount records
existsAction()GET /:id/existsCheck if record exists

Authorization Rules

RuleDescription
everyoneNo authentication required
authenticatedMust be logged in
ownerMust own the resource
adminMust have admin role
ownerOrAdminOwner or admin
defineRule(name, fn)Create custom rule

Drivers

DriverImportDescription
prisma(client)nevr/drivers/prismaPrisma ORM driver

Adapters

AdapterImportDescription
expressAdapter(app)nevr/adapters/expressExpress.js adapter
honoAdapter(app)nevr/adapters/honoHono adapter

Plugin Functions

FunctionDescription
createPlugin(options)Create a plugin (recommended)
createPluginFactory(fn)Create configurable plugin
endpoint(path, config)Define typed endpoint
detectPluginType(plugin)Detect plugin type
isValidPlugin(plugin)Check if valid plugin
schemaFromEntities(entities)Create schema from entities

Error Classes

ClassHTTPDescription
NevrErrorClass-Base error class
EntityNotFoundError404Entity not found
ValidationFailedError400Validation failed
AuthenticationError401Authentication required
AuthorizationError403Permission denied
ConflictError409Resource conflict
PluginError500Plugin error
ConfigurationError500Configuration error
DatabaseError500Database error

Error Builders

FunctionStatusDescription
validationError(errors)400Validation error response
unauthorizedError(msg?)401Unauthorized response
forbiddenError(msg?)403Forbidden response
notFoundError(msg?)404Not found response
conflictError(msg?)409Conflict response
internalError(msg?)500Internal error response
handleError(error)-Convert error to response

See Errors Reference for all error utilities.


Router Utilities

FunctionDescription
matchRoute(path, pattern)Match path to route pattern
pluralize(name)Pluralize entity name
singularize(name)Singularize entity name

See Router Reference for details.


Service Container

ExportDescription
ServiceContainerMain container class
ScopedContainerPer-request scoped container
createScope(container)Create scoped container
createService(id, factory)Create service definition
lazyService(id)Create lazy service reference
getGlobalContainer()Get global container
setGlobalContainer(c)Set global container

Logger & Utils

ExportDescription
getLogger()Get current logger
setLogger(logger)Set custom logger
noopLoggerSilent logger
consoleLoggerConsole-based logger
createPrefixedLogger(prefix, logger)Create prefixed logger
capitalize(str)Capitalize first letter
pascalCase(str)Convert to PascalCase
camelCase(str)Convert to camelCase
kebabCase(str)Convert to kebab-case
snakeCase(str)Convert to snake_case
isValidIdentifier(str)Check valid JS identifier
isValidEntityName(str)Check valid entity name

Workflow Engine

ExportDescription
workflow(steps)Create workflow
runWorkflow(workflow, ctx)Execute workflow
executeWorkflow(steps, ctx)Execute workflow steps
WorkflowBuilderFluent workflow builder
createEntityStep(entity, data)Create entity step
updateEntityStep(entity, where, data)Update entity step
deleteEntityStep(entity, where)Delete entity step

Enhancement Functions

FunctionDescription
createEnhancedDriver(driver, entities)Create enhanced driver
validateCrossFields(data, validators)Cross-field validation
filterReadableFields(data, user)Filter by read access
filterWritableFields(data, user)Filter by write access
hashPassword(password)Hash password with scrypt
verifyPassword(password, hash)Verify password
encryptValue(value)Encrypt field value
decryptValue(value)Decrypt field value

See Enhancements Reference for all functions.


Type Inference

typescript
import type { $Infer, InferEntityData, InferCreateInput } from "nevr"

// Infer entity types from Nevr instance
type User = typeof api.$Infer.Entities["user"]

// Infer entity names
type EntityNames = typeof api.$Infer.EntityNames

// Infer from entity directly
type UserData = InferEntityData<typeof user>
type CreateUserInput = InferCreateInput<typeof user>

See Type Inference Reference for all type utilities.

Released under the MIT License.