Releases
Release notes for the nestjs-odata packages. The canonical source is GitHub Releases — each release links the PRs, commits, and authors that shipped in it. The per-package history below is generated from changesets at release time.
@nestjs-odata/core
2.4.0
Minor Changes
#103
f17cfbeThanks @cberd1509! - Parse each system query option from its own value, decoded exactly once (kuantia-ai/iustum-crm#281).ODataQueryPipeused to join the already-decodedreq.queryvalues with&and split the string again, and decoded only$searchand$applya second time. A value holding&was cut in two ($filter=contains(title,'A %26 B')failed with 400, and$filter=name eq 'x%26$top=1'even set$top), and a literal%in$searchor$apply($search=100%25) failed to decode.ODataQueryPipeparses$filter,$select,$expand(nested options included),$orderby,$top,$skip,$count,$searchand$applyfrom their own values, as NestJS decoded them, in one pass and without decoding again:&,%,+, spaces and quotes ('') inside literals reach the parser unchanged. Its input contract (decoded values by parameter name) is documented on the pipe.- New exports, additive (hence a minor release):
parseQueryOptions(options), with the typesODataQueryOptionValuesandParsedQueryOptions: parses decoded values by name (req.query,URLSearchParams),$count,$searchand$applyincluded.parseQueryString(queryString): parses a raw, percent-encoded query string. It splits on&between parameters only, then decodes each name and value once (+as a space). Malformed percent-encoding is anODataParseError(400).
parseQuery(queryString)keeps its 2.3.0 contract: it splits on every&and uses the values as written, without decoding; the last of repeated options wins.$orderbyitems are split on commas outside string literals and parentheses, soconcat(name,', ')orname eq 'a, b'stay one item (before, they failed to parse).
Behaviour changes for requests (each was a silent misreading before):
- A system query option given more than once is refused with 400, whatever the letter case (
$top=1&$top=2,$top=1&$TOP=2; Part 2 §5). Before, an array value was stringified and the case variants were both read, the last one winning. - A system query option whose value is not a single string (an object such as
$filter[x]=...from an extended query parser, or any other non-string) is refused with 400. Before, it was stringified or ignored.
2.3.0
Minor Changes
#87
46fb9e4Thanks @cberd1509! - OData 4.01$batchconformance: operations run through their routes, changeset responses, query options and one endpoint for every feature module (#64, #65, #67, #73).Security fix (#67):
$batchoperations no longer bypass route guards. Each operation is now dispatched, in process, through the application's HTTP stack (the Express application, or Fastify'sinject()), so it reaches its route with the same middleware, guards (route and global), interceptors, pipes, exception filters and error mapping as the same request sent on its own (Part 1 §11.7). Before, operations were executed directly against TypeORM and the guards, interceptors and pipes of@ODataControllerroutes never ran for them: aDELETEprotected by a role guard answered 403 over HTTP and 204 inside$batch. A guard that denies an operation now answers 403 for it, and fails its whole changeset. Operations inherit the$batchrequest's headers (credentials,Cookie,Accept-Language, custom headers; notContent-*,Prefer,If-Match/If-None-Match,Acceptor connection headers), with their own headers taking precedence. Changesets stay atomic: the changeset's transaction is propagated to its operations throughAsyncLocalStorage, andTypeOrmAutoHandler, row-level scopes and write handlers (ctx.manager) use it;$<Content-ID>references keep working.Behaviour changes:
- Operations need a route (#67): an operation reaches only what a standalone request reaches. An entity set without a controller, or a method without a route (no
@ODataDelete, …), answers 404 inside$batchtoo; before,$batchcould read and write any entity set registered withforFeature(). Route guards, interceptors and pipes now apply to batch operations (see above). - Operations are confined to the service root: a URL that resolves outside it (
/auth/login,../admin, an absolute URL to another path) answers 400 without reaching any route. - A failed changeset is answered with a single
application/httperror response (#64, §11.7.7.5): the failing operation's response as its route sent it (status, headers, OData error), with itsContent-ID, in place of the whole changeset. Before, every request of the changeset got a copy of the error. Operations after the failing one are not executed. Clients that index batch responses by part position must account for it. - A successful changeset is a nested
multipart/mixedpart (§11.7.7.5: the response matches the request one-to-one) with one response per request, each with itsContent-ID. Before, its responses were flattened into the top-level multipart body. - GET operations honour their query options (#65):
$filter,$select,$expand(with nested options),$orderby,$top,$skip,$count,$search,$apply, with the same validation, row-level scopes and response envelope (@odata.context,@odata.count,@odata.nextLink,@odata.etag, annotations) as the standalone request. Before, a collection GET returned every row up tomaxTopas a bare{ value }. GET by key gets@odata.contexttoo, and$count,$metadataor any other route can be batched. - Operation responses are the route's own, unchanged: status, headers (
Content-Type,ETag,Location,Preference-Applied,WWW-Authenticate,Retry-After,OData-Version, your own;Set-Cookieone line per value) and body (binary bodies byte for byte), errors included; only an operation that matched no route gets a library-made OData 404. Operations are asked forAccept-Encoding: identity(the batch request'sAccept-Encodingis not inherited) andContent-Encodingis dropped; HTTP/2 pseudo-headers are never inherited;Content-Lengthis always recomputed.buildBatchResponse()now returns the body as aBuffer, andBatchResponsePart.headers/bodyacceptstring[]values andBufferbodies. - Operation timeout: an operation that does not answer within
batch.operationTimeout(default 30 000 ms) answers 504; inside a changeset that fails and rolls back the changeset. $<Content-ID>references are whole tokens with exact IDs: the operation URL when it is$Nor starts with$N/, and JSON string values of the body that are$Nor start with$N/(@odata.bind).$1no longer matches inside$10or in text such as"costs $1".- Nested
$batchis refused however it is spelled ($BATCH,%24batch), and a$batchreached from inside a batch operation answers 400. - Error mapper context for batch operations (#62 hook): the mapper now runs in the operation's route filter, so
ctx.requestandctx.hostare the operation's own request and host (the$batchrequest isgetODataBatchPart()?.batchRequest);ctx.batchstill describes the operation. Changeset-level failures keepctx.batch.changesetand the$batchrequest. - Write handler, scope and changeset-runner context:
ctx.executionContext/ctx.requestof write handlers and scopes are the operation's own (they used to be the$batchroute's).ctx.batchand, inside a changeset,ctx.managerare still set. - One
BatchControllerper application (#73):forFeature()now imports a staticODataBatchModuleinstead of declaringBatchControlleritself, so a singlePOST {serviceRoot}/$batchserves the entity sets of every feature module. Before, eachforFeature()registered its own controller, the first one won, and parts for another feature's entity sets failed with 500. - Code of your own that writes from an OData route (a custom controller transaction, an injected repository) is not part of a changeset unless it uses
getODataChangesetManager().
Additions:
ODataTypeOrmModule.forRoot({ batch: { enabled?, entitySets?, operationTimeout? } }):enabled: falseturns the endpoint off (404);entitySetsallow-lists the entity sets operations may reach — the resource path's, navigation targets (Products(1)/Supplier) and$expandtargets, nested ones included and whatever the case of the option name ($EXPAND) (403 otherwise, without reaching the route; the service root is taken from the$batchURL, so a global prefix equal to the service root works);operationTimeoutlimits each operation. TokenODATA_BATCH_OPTIONS, typeODataBatchOptions,DEFAULT_BATCH_OPERATION_TIMEOUT.- The batch operation, with the changeset's entity manager as its
changeset, is attached to the operation's request (ODATA_BATCH_PART) as well as kept inAsyncLocalStorage, and read from the request first, so middleware that resumesnext()from a foreign async context (a session store, callback-based auth) cannot make changeset writes commit outside the transaction (Express adapter; Fastify'sinject()relies onAsyncLocalStorage). - typeorm:
getODataChangesetManager(request?),ODataBatchModule. - core:
getODataBatchPart(request?)/runWithODataBatchPart()(the batch operation being handled, for batch-specific policies in guards),ODATA_BATCH_PART,dispatchBatchOperation()(withtimeoutMsand the operation's batch part),BatchOperationTimeoutError,inheritedBatchHeaders(),batchOperationHeaders(),parseBatchUrl(),resolveBatchOperationUrl(),batchErrorContext(),headerValue(),resolveNavigationTarget(),splitKeyPredicate(), and theBatchChangesetResponse/BatchResponseItemtypes.buildBatchResponse()accepts nested changeset responses and keeps each operation'sContent-Type. - Operation URLs may be relative to the service root (
Products(1)), absolute paths or absolute URIs (§11.7.7.1); a nested$batchoperation answers 400. - core: the default error mapping gives 406, 413, 415 and 504 their OData codes (
NotAcceptable,PayloadTooLarge,UnsupportedMediaType,GatewayTimeout) instead ofError.
- Operations need a route (#67): an operation reaches only what a standalone request reaches. An entity set without a controller, or a method without a route (no
#84
ee0b8feThanks @cberd1509! - OData 4.01 query-language conformance (#66, #68, #69):$filteraccepts paths through single-valued navigation properties (category/name eq 'Tools', also after a lambda range variable and in nested$expandfilters). Collection-valued navigation properties still requireany/all; using one in a path is a 400 that says so.- Lambda operators are case-insensitive (
items/ANY(...)), and$it/<path>refers to the entity being filtered, also inside lambda predicates (items/any(d: d/quantity gt $it/totalAmount)). - Nested
$expandoptions$count=true,$searchand$levels(a number ormax, for recursive navigation properties) are parsed, and$expand=nav/$count(optionally with$filter/$search) is accepted.ODataQueryPipereplaces$levelsby the equivalent nested$expands. - New
ODataNotImplementedError, answered with501 Not Implemented(codeNotImplemented, the message is kept) per OData 4.01 Part 1 §9.3.1. - Nested
$expandoptions containing;inside parentheses (a nested$expandwith several options, or a;in a string literal) are no longer split apart.
Behaviour changes (the spec mandates them):
- Nested
$expandoptions that were silently ignored now fail:$compute/$applyinside$expand,nav/$ref,$itinside$expandoptions,$root, and$it/$count/$thispath segments answer 501; unknown nested options (items($foo=1)) answer 400. $countand/$counton a single-valued navigation property answer 400.- A lambda over something that is not a collection-valued navigation property (
category/any(...), an unknown name) answers 400 instead of being ignored. - Navigation paths in
$orderbyanswer 501 (they were a 400).
#85
d073558Thanks @cberd1509! - OData 4.01 protocol conformance of writes, ETags, routing and errors (#63, #70, #71, #75, #76, #77, #78, #79, #80, #81).Behaviour changes (spec-mandated, on by default):
- Unknown properties in write bodies answer 400 (Part 1 §11.4.2: the service MUST fail when it cannot persist a value). POST, PATCH and PUT (HTTP and
$batch, repository path) refuse a property that is not in the entity type, including columns hidden with@ODataExcludeorselect: false, with oneUnknownPropertyentry per property indetails. They were silently ignored before (and hidden columns could be written). Escape hatch:ignoreUnknownProperties: trueinODataModule.forRoot()drops them instead (still never persisted). Bodies handed to write handlers are unchanged. - PUT ignores a body key that differs from the URL key (§11.4.3) and replaces the entity at the URL, over HTTP and in
$batch, instead of answering 400 "Key in body does not match URL key". - Computed properties are ignored on POST/PATCH (§11.4.2):
@CreateDateColumn,@UpdateDateColumn,@VersionColumnand generated non-key columns.$metadataannotates them withCore.Computedand now references the Core vocabulary (edmx:Reference) whenever an annotation is used. If-None-Matchon PATCH, PUT and DELETE answers 412 with no change when it matches the current ETag;*matches any existing entity (§8.2.5). HTTP and$batch.If-Match/If-None-Matchare read from the request byTypeOrmAutoHandlerwhen the controller doesn't pass them, so controllers that never bound@Headers('if-match')now get 412 on a staleIf-Match. An explicitifMatchargument still wins.ETagon rows without an ETag value: an entity whose ETag column is absent from the row (e.g. not selected) gets no ETag instead of the ETag ofundefined.
Additions:
- Canonical entity URLs are routed (URL Conventions §4.3.1):
GET/PATCH/PUT/DELETE /odata/Products(1)and composite/odata/OrderItems(orderId=1,productId=2)reach the key routes, soLocationand@odata.id(unchanged, canonical) are resolvable.ODataModulerewrites the URL to/Set/keybefore routing on the Express adapter, only for registered entity sets;/Set/keykeeps working. Content-Languageon every error response and$batcherror part (§9.4): anerrorMapperresult's newlanguage, else the newerrorLanguagemodule option, elseen.buildODataErrorResponse()returnslanguageand takes an optional default language. Mappings with an invalid language tag fall back to the default mapping; an invaliderrorLanguagefails at startup.Prefer: return=minimal(§8.2.8.7) on POST, PATCH and PUT answers 204 withPreference-Applied(POST:LocationandOData-EntityId);return=representationis confirmed withPreference-Applied;$select/$expandimply representation. Also per$batchpart ($Nreferences to a 204 create keep working).requireIfMatchperforFeature()item: PATCH, PUT and DELETE withoutIf-Matchanswer 428 with no change (HTTP,$batch, write handlers), and$metadataannotates the entity set withCore.OptimisticConcurrency. Write handlers getctx.requireIfMatchandctx.ifNoneMatch.@odata.etagon each entity of a collection for entity sets with an ETag (JSON §4.5.10).- 304 Not Modified no longer logs "Cannot set headers after they are sent": the interceptor signals an empty response that
ODataExceptionFiltersends (also used for 204). - Express
etagwarning: a startup warning while Express'setagsetting is on (its hash ETags on errors, collections and$metadataare not OData ETags). The library doesn't change the setting; docs recommendapp.set('etag', false). - The default error mapping keeps valid
detailsof 4xxHttpExceptions with an OData-shaped body, and maps 428 toPreconditionRequired. - New exports: core
resolveReturnPreference,rewriteCanonicalKeyUrl,isLanguageTag,DEFAULT_ERROR_LANGUAGE,EdmProperty.computed,EdmEntitySet.optimisticConcurrency; typeormprepareWriteBody.
- Unknown properties in write bodies answer 400 (Part 1 §11.4.2: the service MUST fail when it cannot persist a value). POST, PATCH and PUT (HTTP and
Patch Changes
#102
dd29d11Thanks @cberd1509! -$filterliterals (#101):- An unquoted GUID that starts with a digit (
id eq 12345678-1234-1234-1234-123456789abc) parses anywhere in the expression; before, it only parsed at the very end of the filter, and failed with a 400 when anything followed it. - Bare dates (
dueDate ge 2026-11-01) and date-times with a time zone (createdAt lt 2026-11-01T10:30:00Z,…-05:00) parse. They becomeLiteralnodes withliteralKind: 'date'(new) or'dateTimeOffset', and a string value. The lexer never produced them before, so they failed with a 400.
- An unquoted GUID that starts with a digit (
2.2.0
Minor Changes
#62
b502a64Thanks @cberd1509! - Error-mapping hook.@nestjs-odata/core:- New
errorMapperoption onODataModule.forRoot()/forRootAsync():(exception, ctx) => ODataErrorMapping | undefined, synchronous. A mapping hasstatus,code,message, and optionallytarget,detailsandinnererror, and is sent in OData v4 JSON error format. Every field is validated. Returningundefinedkeeps the default mapping, and so do a mapper that throws, returns a Promise or returns an invalid mapping (logged as a warning). - It runs on the routes of the OData route decorators,
$metadataand the service document. Plain Nest routes on an@ODataControllerkeep the application's global filters and can opt in with@UseFilters(ODataExceptionFilter). - The default mapping keeps the 4xx/5xx status of non-
HttpExceptionerrors carrying a numericstatus/statusCode, and never sends the message of a 5xx error (also for 5xxHttpExceptions, whose message was sent before). - Error responses always use
Content-Type: application/json. HttpExceptions with an OData-shaped body keep their message instead of "Http Exception", and 412 maps toPreconditionFailed.- New exports:
buildODataErrorResponse,httpStatusToODataCode,odataErrorBodyand theODataErrorMapper*types.
- New
@nestjs-odata/typeorm: each failing$batchoperation goes through the mapper, withctx.batch = { method, url, contentId }and the$batchrequest. Its status and body become the part's response. A changeset that fails as a whole getsctx.batch = { changeset: true }.- OData conformance (JSON Format 4.01 §21.1): mapper results need non-empty
codeandmessage(also indetails), andtargetmay benull. The defaultdetailsof parse and validation errors now carrycodeandmessagetoo (QueryOption,AvailableProperties); theirtargetandvalueare unchanged. - The library's own
$batchpart errors (404, missing key, 412, 405, …) also go through the mapper, and the mapper context'srequestcomes from the OData request context. The default mapping follows an error'scausechain to a 4xx, over HTTP and in$batch.
#59
9b4a574Thanks @cberd1509! - Support NestJS 12 and TypeORM 1.- Widen the peer dependencies to
@nestjs/common,@nestjs/coreand@nestjs/typeorm^10 || ^11 || ^12, andtypeorm^0.3.0 || ^1.0.0. @nestjs-odata/corenow declares@nestjs/coreas a peer dependency; it already importedReflectorfrom it.@nestjs-odata/typeormno longer deep-imports@nestjs/typeorm/dist/...in its published type declarations.@nestjs/typeorm12 only exports its root entry, so that import did not resolve for consumers. The type is now exported asEntityClassOrSchema.@nestjs-odata/typeormnow requires@nestjs-odata/core>=2.2.0(the first core release with NestJS 12 peers).- The workspace develops and tests on NestJS 12.3,
@nestjs/typeorm12.0 and TypeORM 1.1, so every existing suite (unit and e2e) runs on them. - SQLite-based drivers other than
sqlite(better-sqlite3,sqljs,capacitor,expo, …) now get the SQLite dialect for date (year(), …) andindexof()filters. Before, they fell back to ANSI SQL that SQLite cannot run. - The query translator reads the driver type from
EntityManager.dataSourceinstead of the deprecatedconnectionalias. EntityClassOrSchemais derived fromTypeOrmModule.forFeature()'s parameter type, so it always matches what@nestjs/typeormaccepts.
- Widen the peer dependencies to
#60
8fd7f75Thanks @cberd1509! - Row-level scopes.@nestjs-odata/typeorm:ODataTypeOrmModule.forFeature()items accept ascope, and the options acceptdefaultScopeandimports. A scope is(qb, ctx) => void | Promise<void>or an injectableODataScopeclass.ctxcarries the entity set, the EDM type, the TypeORM metadata, the alias, the operation, the navigation path, the NestExecutionContextand the request. The scope restricts collection reads,$count,$apply, by-key reads, every$expandpath (in the JOIN condition, at any depth), lambdas (any/all) in$filter,$batch, and the existence checks ofPATCH/PUT/DELETEinTypeOrmAutoHandlerand$batch. NewTypeOrmScopeServicefor custom controllers;TypeOrmQueryTranslator.translate()takes an optional scope plan.@nestjs-odata/core: newrequireScopeoption fails closed: the app refuses to start while an entity set has no scope, and requests that reach one fail. NewgetODataRequestContext()/runWithODataRequestContext()and a globalODataRequestContextInterceptor, registered byforRoot(), that exposes the currentExecutionContextand request to hooks.- Fixes:
- Nested query options inside
$expand(...)are applied. They were ignored, because the target type was looked up by its qualified name. - A nested
$filternow restricts the expanded rows (in the JOIN), not the parent rows. - A nested
$selectno longer replaces the root selection. - Lambda predicates such as
items/any(i: i/quantity gt 1)work: the pipe validatesi/quantityagainst the collection's entity type, and the translator maps it to the lambda alias.
- Nested query options inside
- Hardening:
- Options inside
$expand(...)are validated against the related type; unknown or excluded properties give 400 instead of 500. - TypeORM
select: falsecolumns are excluded from the EDM, like@ODataExclude. - Key properties in a
PATCHbody are ignored, over HTTP and in$batch(OData 4.01 Part 1 §11.4.3), so a body key can no longer redirect the update to another row. - Scoped writes run the scope check and the write in one transaction, with a row lock where the driver supports it.
- Scoped by-key reads load eager relations.
- Each scope runs once per entity set and operation for a request.
- Under
requireScope, a missing$expandor lambda lookup fails. - Inside a lambda, properties without the range variable refer to the outer entity, and predicates can use
and,orandnot.
- Options inside
@nestjs-odata/typeormpeers:@nestjs-odata/core >=2.2.0(the core release with request context andrequireScope) and@nestjs/core.navigationTargetTypeName: now exported from@nestjs-odata/core.@nestjs-odata/core: newEdmRegistry.getEntitySetByTypeName().
Patch Changes
- #61
5159ce4Thanks @cberd1509! - Custom write handlers.@nestjs-odata/typeorm:ODataTypeOrmModule.forFeature()items acceptwriteHandlers: anODataWriteHandlersobject or an injectable class withcreate,deepInsert,update(PATCH),replace(PUT) anddelete. They route the entity set's writes, including$batch, through application code instead of the repository. A missing handler answers 405.- Handlers receive the parsed body, the parsed key, and an
ODataWriteContext: entity set, EDM type, operation, raw key,If-Match, NestExecutionContext, request, and in a changeset the transaction'sEntityManagerand the batch info. They return the entity to serialize. - New
etagitem option (a property name or a function) sets the entity set's ETag source. It overrides@ODataETag/@UpdateDateColumn, is sent on by-key reads and handler-written responses, andetagMatches()/formatWeakETag()are exported. - New
ODataTypeOrmModule.forRoot({ changesetRunner })runs$batchchangesets inside the application's own unit of work (or provide the newODATA_CHANGESET_RUNNERtoken). The default is aQueryRunnertransaction exposed to handlers asctx.manager. A runner that wraps errors no longer hides the failing part's status. $batchresponse parts now carry theirLocationandETagheaders, and entity bodies their@odata.etag, for every ETag source (also@ODataETag/@UpdateDateColumn) and on GET by key. Before, part headers were dropped.If-Match: *and ETag lists are accepted for every ETag source.- A handler that returns no entity fails with 500 (HTTP and
$batch); deep inserts whose nested entities belong to a handler-backed entity set are refused with 400;nullnavigation values no longer count as a deep insert. $batchkeeps the status of anHttpExceptionfound in an error'scausechain.- Scoped writes only take a row lock inside a transaction (PostgreSQL refuses
FOR UPDATEoutside one).
@nestjs-odata/core: POST responses whose entity carries an adapter-provided ETag get theETagheader and@odata.etag.TypeOrmETagProvider.validateIfMatch()now uses the same comparison as the write paths (*, lists), andcomputeETag()the same format asformatWeakETag(). NewhasEntityETag()helper.- OData conformance: a 405 from write handlers carries an
Allowheader (Part 1 §9.2.2); repository creates send the entity's ETag and@odata.etag(instead of none);$batchrepository writes checkIf-Matchlike the HTTP routes (412).
2.1.0
Minor Changes
#35
d204ea2Thanks @cberd1509! - Dependency bumps to the latest safe versions, plus a focused round of fixes and DX improvements surfaced by a real-world multi-entity integration.Bug fixes
@nestjs-odata/typeorm:TypeOrmAutoHandlerno longer mis-routes requests to the first-registered entity whenforFeature([A, B, ...])is called with multiple entities. The handler now resolves the correctRepositoryper request from the entity-set name viaDataSource+EdmRegistry.TypeOrmQueryTranslator.translate()accepts an optional per-request repo override (backwards compatible for single-entity callers). Eliminates the downstream "column does not exist" 500 that hit any filter referencing a column unique to the second-registered entity.
New features / DX improvements
@nestjs-odata/typeorm:ODataTypeOrmModule.forFeature()now accepts a mixed array of entity classes and{ entity, name }config objects so you can override the OData entity-set name without touching the entity class. Avoids the/odata/UserEntitiesugliness that comes from theEntitysuffix convention — pass{ entity: UserEntity, name: 'Users' }to expose/odata/Usersinstead. Override wins over@ODataEntitySetdecorator and default pluralization.@nestjs-odata/typeorm:forFeature()accepts a newoptions.controllersarray. When provided, controllers are both PATH_METADATA-patched withserviceRootAND registered in the dynamic module — eliminating the "declare in two places" papercut (ODataModule .forRoot({controllers})+@Module({controllers})). Single declaration inforFeatureis now sufficient for DI resolution.@nestjs-odata/typeorm:@odata.nextLinkis now built from `serviceRoot- entitySetName
(notreq.originalUrl), so it's prefix-consistent with@odata.contextand@odata.id. OData v4 clients (Excel, Olingo, odata2ts) can now navigate paginated responses when the app is mounted under a NestsetGlobalPrefix`.
- entitySetName
@nestjs-odata/core: NewODataModule.globalPrefixExclude(serviceRoot?)static helper returning the Express 5 splat-style exclude patterns forapp.setGlobalPrefix(). Replaces hand-crafted'api/odata{/*splat}'snippets — callapp.setGlobalPrefix('api', { exclude: ODataModule .globalPrefixExclude() }).
Tests
- New e2e regression suite
apps/test-app/test/multi-entity-disambiguation .e2e-spec.ts(16 tests) covering: multi-entity routing for list / get-by-key / $count / POST / PATCH / DELETE / multi-word$filterliteral / entity registration-order swap, the{ entity, name }override, the single-declarationforFeature({ controllers })pattern, the prefix- consistent@odata.nextLink, and theglobalPrefixExcludehelper.
Docs
docs/guide/getting-started.md: new sections on multi-entity registration- custom set names, and
setGlobalPrefix()integration.
- custom set names, and
docs/guide/configuration.md: documents the{ entity, name }form, thecontrollersoption onforFeature, and the global-prefix workflow.docs/api/module.md: full reference forODataModule.globalPrefixExclude()and the expandedODataTypeOrmModule.forFeature()signature including the newODataTypeOrmFeatureItemtype.docs/guide/troubleshooting.md: three new entries for the common gotchas (double-prefixed routes, uglyEntitiesURL suffix, multi-entity wrong- row symptom).
Backwards compatibility
All changes are additive. Existing
forFeature([Product, Order])calls andforRoot({ controllers })+@Module({ controllers })setups continue to work unchanged. The test-app's existing 197 e2e tests pass without modification.
2.0.0
Major Changes
0966a8cThanks @cberd1509! - Initial v1.0.0 release — OData v4 for NestJS with TypeORM integrationFeatures:
- Auto-derive OData EDM from TypeORM entities (zero double-declaration)
- Full query surface: $filter, $select, $orderby, $top, $skip, $count, $expand
- Filter functions: string, date/time, arithmetic, lambda (any/all)
- CRUD operations with PATCH, PUT (full replace), and deep inserts
- $batch with multipart/mixed and Content-ID cross-references
- $search with pluggable search providers
- $apply aggregation pipelines (groupby, aggregate, filter, compute)
- Response annotations (@odata.id, @odata.type, @odata.etag)
- ETag-based optimistic concurrency control
- Configurable security limits and validation
- $metadata endpoint with CSDL XML
- Zero-boilerplate module API (forRoot/forFeature)
@nestjs-odata/typeorm
3.3.0
Minor Changes
#103
f17cfbeThanks @cberd1509! - Query option values are no longer split on an encoded&(kuantia-ai/iustum-crm#281). Requires@nestjs-odata/core2.4.0 or later (parseQueryOptions).- Security fix: the
batch.entitySetsallow-list checks every$expandand fails closed. It re-joined each decoded$expandvalue into a query string, so a nested literal holding&($expand=ticket($filter=subject eq 'A %26 B')) failed to parse there, and the option was skipped, letting the operation expand into an entity set outside the allow-list. The value is now parsed as is, and an$expandthe allow-list cannot parse is refused with 403 instead of being skipped (before, the route answered it with 400). @odata.nextLinkkeeps the request's query intact: it is read withURLSearchParams(split on&between parameters,+read as a space, malformed percent-encoding tolerated); every value of a repeated custom parameter is kept; names and values are percent-encoded (a leading$stays as is); existing$skip/$topentries are replaced whatever their letter case.
- Security fix: the
Patch Changes
- Updated dependencies [
f17cfbe]:- @nestjs-odata/core@2.4.0
3.2.0
Minor Changes
#87
46fb9e4Thanks @cberd1509! - OData 4.01$batchconformance: operations run through their routes, changeset responses, query options and one endpoint for every feature module (#64, #65, #67, #73).Security fix (#67):
$batchoperations no longer bypass route guards. Each operation is now dispatched, in process, through the application's HTTP stack (the Express application, or Fastify'sinject()), so it reaches its route with the same middleware, guards (route and global), interceptors, pipes, exception filters and error mapping as the same request sent on its own (Part 1 §11.7). Before, operations were executed directly against TypeORM and the guards, interceptors and pipes of@ODataControllerroutes never ran for them: aDELETEprotected by a role guard answered 403 over HTTP and 204 inside$batch. A guard that denies an operation now answers 403 for it, and fails its whole changeset. Operations inherit the$batchrequest's headers (credentials,Cookie,Accept-Language, custom headers; notContent-*,Prefer,If-Match/If-None-Match,Acceptor connection headers), with their own headers taking precedence. Changesets stay atomic: the changeset's transaction is propagated to its operations throughAsyncLocalStorage, andTypeOrmAutoHandler, row-level scopes and write handlers (ctx.manager) use it;$<Content-ID>references keep working.Behaviour changes:
- Operations need a route (#67): an operation reaches only what a standalone request reaches. An entity set without a controller, or a method without a route (no
@ODataDelete, …), answers 404 inside$batchtoo; before,$batchcould read and write any entity set registered withforFeature(). Route guards, interceptors and pipes now apply to batch operations (see above). - Operations are confined to the service root: a URL that resolves outside it (
/auth/login,../admin, an absolute URL to another path) answers 400 without reaching any route. - A failed changeset is answered with a single
application/httperror response (#64, §11.7.7.5): the failing operation's response as its route sent it (status, headers, OData error), with itsContent-ID, in place of the whole changeset. Before, every request of the changeset got a copy of the error. Operations after the failing one are not executed. Clients that index batch responses by part position must account for it. - A successful changeset is a nested
multipart/mixedpart (§11.7.7.5: the response matches the request one-to-one) with one response per request, each with itsContent-ID. Before, its responses were flattened into the top-level multipart body. - GET operations honour their query options (#65):
$filter,$select,$expand(with nested options),$orderby,$top,$skip,$count,$search,$apply, with the same validation, row-level scopes and response envelope (@odata.context,@odata.count,@odata.nextLink,@odata.etag, annotations) as the standalone request. Before, a collection GET returned every row up tomaxTopas a bare{ value }. GET by key gets@odata.contexttoo, and$count,$metadataor any other route can be batched. - Operation responses are the route's own, unchanged: status, headers (
Content-Type,ETag,Location,Preference-Applied,WWW-Authenticate,Retry-After,OData-Version, your own;Set-Cookieone line per value) and body (binary bodies byte for byte), errors included; only an operation that matched no route gets a library-made OData 404. Operations are asked forAccept-Encoding: identity(the batch request'sAccept-Encodingis not inherited) andContent-Encodingis dropped; HTTP/2 pseudo-headers are never inherited;Content-Lengthis always recomputed.buildBatchResponse()now returns the body as aBuffer, andBatchResponsePart.headers/bodyacceptstring[]values andBufferbodies. - Operation timeout: an operation that does not answer within
batch.operationTimeout(default 30 000 ms) answers 504; inside a changeset that fails and rolls back the changeset. $<Content-ID>references are whole tokens with exact IDs: the operation URL when it is$Nor starts with$N/, and JSON string values of the body that are$Nor start with$N/(@odata.bind).$1no longer matches inside$10or in text such as"costs $1".- Nested
$batchis refused however it is spelled ($BATCH,%24batch), and a$batchreached from inside a batch operation answers 400. - Error mapper context for batch operations (#62 hook): the mapper now runs in the operation's route filter, so
ctx.requestandctx.hostare the operation's own request and host (the$batchrequest isgetODataBatchPart()?.batchRequest);ctx.batchstill describes the operation. Changeset-level failures keepctx.batch.changesetand the$batchrequest. - Write handler, scope and changeset-runner context:
ctx.executionContext/ctx.requestof write handlers and scopes are the operation's own (they used to be the$batchroute's).ctx.batchand, inside a changeset,ctx.managerare still set. - One
BatchControllerper application (#73):forFeature()now imports a staticODataBatchModuleinstead of declaringBatchControlleritself, so a singlePOST {serviceRoot}/$batchserves the entity sets of every feature module. Before, eachforFeature()registered its own controller, the first one won, and parts for another feature's entity sets failed with 500. - Code of your own that writes from an OData route (a custom controller transaction, an injected repository) is not part of a changeset unless it uses
getODataChangesetManager().
Additions:
ODataTypeOrmModule.forRoot({ batch: { enabled?, entitySets?, operationTimeout? } }):enabled: falseturns the endpoint off (404);entitySetsallow-lists the entity sets operations may reach — the resource path's, navigation targets (Products(1)/Supplier) and$expandtargets, nested ones included and whatever the case of the option name ($EXPAND) (403 otherwise, without reaching the route; the service root is taken from the$batchURL, so a global prefix equal to the service root works);operationTimeoutlimits each operation. TokenODATA_BATCH_OPTIONS, typeODataBatchOptions,DEFAULT_BATCH_OPERATION_TIMEOUT.- The batch operation, with the changeset's entity manager as its
changeset, is attached to the operation's request (ODATA_BATCH_PART) as well as kept inAsyncLocalStorage, and read from the request first, so middleware that resumesnext()from a foreign async context (a session store, callback-based auth) cannot make changeset writes commit outside the transaction (Express adapter; Fastify'sinject()relies onAsyncLocalStorage). - typeorm:
getODataChangesetManager(request?),ODataBatchModule. - core:
getODataBatchPart(request?)/runWithODataBatchPart()(the batch operation being handled, for batch-specific policies in guards),ODATA_BATCH_PART,dispatchBatchOperation()(withtimeoutMsand the operation's batch part),BatchOperationTimeoutError,inheritedBatchHeaders(),batchOperationHeaders(),parseBatchUrl(),resolveBatchOperationUrl(),batchErrorContext(),headerValue(),resolveNavigationTarget(),splitKeyPredicate(), and theBatchChangesetResponse/BatchResponseItemtypes.buildBatchResponse()accepts nested changeset responses and keeps each operation'sContent-Type. - Operation URLs may be relative to the service root (
Products(1)), absolute paths or absolute URIs (§11.7.7.1); a nested$batchoperation answers 400. - core: the default error mapping gives 406, 413, 415 and 504 their OData codes (
NotAcceptable,PayloadTooLarge,UnsupportedMediaType,GatewayTimeout) instead ofError.
- Operations need a route (#67): an operation reaches only what a standalone request reaches. An entity set without a controller, or a method without a route (no
#84
ee0b8feThanks @cberd1509! - OData 4.01 query-language conformance (#66, #68, #69, #72, #74):$filteron single-valued navigation paths (category/name eq 'Tools',store/region/name): rendered as a correlated subquery, applying the row-level scope of every entity set on the path (a related row outside its scope reads asnull). Works insideor,not, string functions, lambda predicates and nested$expandfilters.- Lambdas (
any/all) over many-to-many navigation properties, through the junction table, applying the target's row-level scope like one-to-many lambdas. - Nested
$expand$count=true(nav@odata.count) and$expand=nav/$count: one grouped, scopedCOUNTquery per expand item, counting the rows matching the nested$filter/$searchand ignoring$top/$skip. - Nested
$expand$search, through the search provider (501 when none is registered). - Nested
$top/$skipon one-to-many navigations are paged in SQL withROW_NUMBER() OVER (PARTITION BY <foreign key> ...)on SQLite, PostgreSQL, CockroachDB, SQL Server and Oracle; other drivers, many-to-many navigations and composite keys fall back to in-memory slicing.TranslateResult.expandPaginationMap(andapplyExpandPagination) are now keyed by expand path (store/items), so two expand paths ending in the same navigation property keep their own options.
Fixes:
$filterwithorwas rendered asAND(a or breturned the rows matching both). It now renders(a) OR (b).- A nested
$orderbyinside$expandreplaced the ordering of the parent rows ($orderby=id&$expand=items($orderby=qty)); it is now appended after it. notapplied to a lambda (not items/any(...)) produced invalid SQL; it now negates theEXISTS.eq null/ne nullrendered= NULL/!= NULL, which never match; they now renderIS NULL/IS NOT NULL.- Comparing two properties at the top level of
$filter(qty gt minQty) compared againstNULL; the right-hand expression is now rendered. contains/startswith/endswithkeep the parameters of their property expression.
#85
d073558Thanks @cberd1509! - OData 4.01 protocol conformance of writes, ETags, routing and errors (#63, #70, #71, #75, #76, #77, #78, #79, #80, #81).Behaviour changes (spec-mandated, on by default):
- Unknown properties in write bodies answer 400 (Part 1 §11.4.2: the service MUST fail when it cannot persist a value). POST, PATCH and PUT (HTTP and
$batch, repository path) refuse a property that is not in the entity type, including columns hidden with@ODataExcludeorselect: false, with oneUnknownPropertyentry per property indetails. They were silently ignored before (and hidden columns could be written). Escape hatch:ignoreUnknownProperties: trueinODataModule.forRoot()drops them instead (still never persisted). Bodies handed to write handlers are unchanged. - PUT ignores a body key that differs from the URL key (§11.4.3) and replaces the entity at the URL, over HTTP and in
$batch, instead of answering 400 "Key in body does not match URL key". - Computed properties are ignored on POST/PATCH (§11.4.2):
@CreateDateColumn,@UpdateDateColumn,@VersionColumnand generated non-key columns.$metadataannotates them withCore.Computedand now references the Core vocabulary (edmx:Reference) whenever an annotation is used. If-None-Matchon PATCH, PUT and DELETE answers 412 with no change when it matches the current ETag;*matches any existing entity (§8.2.5). HTTP and$batch.If-Match/If-None-Matchare read from the request byTypeOrmAutoHandlerwhen the controller doesn't pass them, so controllers that never bound@Headers('if-match')now get 412 on a staleIf-Match. An explicitifMatchargument still wins.ETagon rows without an ETag value: an entity whose ETag column is absent from the row (e.g. not selected) gets no ETag instead of the ETag ofundefined.
Additions:
- Canonical entity URLs are routed (URL Conventions §4.3.1):
GET/PATCH/PUT/DELETE /odata/Products(1)and composite/odata/OrderItems(orderId=1,productId=2)reach the key routes, soLocationand@odata.id(unchanged, canonical) are resolvable.ODataModulerewrites the URL to/Set/keybefore routing on the Express adapter, only for registered entity sets;/Set/keykeeps working. Content-Languageon every error response and$batcherror part (§9.4): anerrorMapperresult's newlanguage, else the newerrorLanguagemodule option, elseen.buildODataErrorResponse()returnslanguageand takes an optional default language. Mappings with an invalid language tag fall back to the default mapping; an invaliderrorLanguagefails at startup.Prefer: return=minimal(§8.2.8.7) on POST, PATCH and PUT answers 204 withPreference-Applied(POST:LocationandOData-EntityId);return=representationis confirmed withPreference-Applied;$select/$expandimply representation. Also per$batchpart ($Nreferences to a 204 create keep working).requireIfMatchperforFeature()item: PATCH, PUT and DELETE withoutIf-Matchanswer 428 with no change (HTTP,$batch, write handlers), and$metadataannotates the entity set withCore.OptimisticConcurrency. Write handlers getctx.requireIfMatchandctx.ifNoneMatch.@odata.etagon each entity of a collection for entity sets with an ETag (JSON §4.5.10).- 304 Not Modified no longer logs "Cannot set headers after they are sent": the interceptor signals an empty response that
ODataExceptionFiltersends (also used for 204). - Express
etagwarning: a startup warning while Express'setagsetting is on (its hash ETags on errors, collections and$metadataare not OData ETags). The library doesn't change the setting; docs recommendapp.set('etag', false). - The default error mapping keeps valid
detailsof 4xxHttpExceptions with an OData-shaped body, and maps 428 toPreconditionRequired. - New exports: core
resolveReturnPreference,rewriteCanonicalKeyUrl,isLanguageTag,DEFAULT_ERROR_LANGUAGE,EdmProperty.computed,EdmEntitySet.optimisticConcurrency; typeormprepareWriteBody.
- Unknown properties in write bodies answer 400 (Part 1 §11.4.2: the service MUST fail when it cannot persist a value). POST, PATCH and PUT (HTTP and
Patch Changes
#102
dd29d11Thanks @cberd1509! -$filtertranslation (#101):- Lambda predicates (
notes/any(n: n/isPinned eq true),all) now render the range variable's properties with their database column names (@Column({ name }), naming strategies), as top-level properties already were. Before, the property name was used as the column name, so a property with a different column name failed with a 500. null eq prop/null ne prop(operands reversed) renderIS NULL/IS NOT NULLlikeprop eq null/prop ne null. Before, they renderedNULL = prop, which never matches.
- Lambda predicates (
Updated dependencies [
46fb9e4,dd29d11,ee0b8fe,d073558]:- @nestjs-odata/core@2.3.0
3.1.0
Minor Changes
#62
b502a64Thanks @cberd1509! - Error-mapping hook.@nestjs-odata/core:- New
errorMapperoption onODataModule.forRoot()/forRootAsync():(exception, ctx) => ODataErrorMapping | undefined, synchronous. A mapping hasstatus,code,message, and optionallytarget,detailsandinnererror, and is sent in OData v4 JSON error format. Every field is validated. Returningundefinedkeeps the default mapping, and so do a mapper that throws, returns a Promise or returns an invalid mapping (logged as a warning). - It runs on the routes of the OData route decorators,
$metadataand the service document. Plain Nest routes on an@ODataControllerkeep the application's global filters and can opt in with@UseFilters(ODataExceptionFilter). - The default mapping keeps the 4xx/5xx status of non-
HttpExceptionerrors carrying a numericstatus/statusCode, and never sends the message of a 5xx error (also for 5xxHttpExceptions, whose message was sent before). - Error responses always use
Content-Type: application/json. HttpExceptions with an OData-shaped body keep their message instead of "Http Exception", and 412 maps toPreconditionFailed.- New exports:
buildODataErrorResponse,httpStatusToODataCode,odataErrorBodyand theODataErrorMapper*types.
- New
@nestjs-odata/typeorm: each failing$batchoperation goes through the mapper, withctx.batch = { method, url, contentId }and the$batchrequest. Its status and body become the part's response. A changeset that fails as a whole getsctx.batch = { changeset: true }.- OData conformance (JSON Format 4.01 §21.1): mapper results need non-empty
codeandmessage(also indetails), andtargetmay benull. The defaultdetailsof parse and validation errors now carrycodeandmessagetoo (QueryOption,AvailableProperties); theirtargetandvalueare unchanged. - The library's own
$batchpart errors (404, missing key, 412, 405, …) also go through the mapper, and the mapper context'srequestcomes from the OData request context. The default mapping follows an error'scausechain to a 4xx, over HTTP and in$batch.
#59
9b4a574Thanks @cberd1509! - Support NestJS 12 and TypeORM 1.- Widen the peer dependencies to
@nestjs/common,@nestjs/coreand@nestjs/typeorm^10 || ^11 || ^12, andtypeorm^0.3.0 || ^1.0.0. @nestjs-odata/corenow declares@nestjs/coreas a peer dependency; it already importedReflectorfrom it.@nestjs-odata/typeormno longer deep-imports@nestjs/typeorm/dist/...in its published type declarations.@nestjs/typeorm12 only exports its root entry, so that import did not resolve for consumers. The type is now exported asEntityClassOrSchema.@nestjs-odata/typeormnow requires@nestjs-odata/core>=2.2.0(the first core release with NestJS 12 peers).- The workspace develops and tests on NestJS 12.3,
@nestjs/typeorm12.0 and TypeORM 1.1, so every existing suite (unit and e2e) runs on them. - SQLite-based drivers other than
sqlite(better-sqlite3,sqljs,capacitor,expo, …) now get the SQLite dialect for date (year(), …) andindexof()filters. Before, they fell back to ANSI SQL that SQLite cannot run. - The query translator reads the driver type from
EntityManager.dataSourceinstead of the deprecatedconnectionalias. EntityClassOrSchemais derived fromTypeOrmModule.forFeature()'s parameter type, so it always matches what@nestjs/typeormaccepts.
- Widen the peer dependencies to
#60
8fd7f75Thanks @cberd1509! - Row-level scopes.@nestjs-odata/typeorm:ODataTypeOrmModule.forFeature()items accept ascope, and the options acceptdefaultScopeandimports. A scope is(qb, ctx) => void | Promise<void>or an injectableODataScopeclass.ctxcarries the entity set, the EDM type, the TypeORM metadata, the alias, the operation, the navigation path, the NestExecutionContextand the request. The scope restricts collection reads,$count,$apply, by-key reads, every$expandpath (in the JOIN condition, at any depth), lambdas (any/all) in$filter,$batch, and the existence checks ofPATCH/PUT/DELETEinTypeOrmAutoHandlerand$batch. NewTypeOrmScopeServicefor custom controllers;TypeOrmQueryTranslator.translate()takes an optional scope plan.@nestjs-odata/core: newrequireScopeoption fails closed: the app refuses to start while an entity set has no scope, and requests that reach one fail. NewgetODataRequestContext()/runWithODataRequestContext()and a globalODataRequestContextInterceptor, registered byforRoot(), that exposes the currentExecutionContextand request to hooks.- Fixes:
- Nested query options inside
$expand(...)are applied. They were ignored, because the target type was looked up by its qualified name. - A nested
$filternow restricts the expanded rows (in the JOIN), not the parent rows. - A nested
$selectno longer replaces the root selection. - Lambda predicates such as
items/any(i: i/quantity gt 1)work: the pipe validatesi/quantityagainst the collection's entity type, and the translator maps it to the lambda alias.
- Nested query options inside
- Hardening:
- Options inside
$expand(...)are validated against the related type; unknown or excluded properties give 400 instead of 500. - TypeORM
select: falsecolumns are excluded from the EDM, like@ODataExclude. - Key properties in a
PATCHbody are ignored, over HTTP and in$batch(OData 4.01 Part 1 §11.4.3), so a body key can no longer redirect the update to another row. - Scoped writes run the scope check and the write in one transaction, with a row lock where the driver supports it.
- Scoped by-key reads load eager relations.
- Each scope runs once per entity set and operation for a request.
- Under
requireScope, a missing$expandor lambda lookup fails. - Inside a lambda, properties without the range variable refer to the outer entity, and predicates can use
and,orandnot.
- Options inside
@nestjs-odata/typeormpeers:@nestjs-odata/core >=2.2.0(the core release with request context andrequireScope) and@nestjs/core.navigationTargetTypeName: now exported from@nestjs-odata/core.@nestjs-odata/core: newEdmRegistry.getEntitySetByTypeName().
#61
5159ce4Thanks @cberd1509! - Custom write handlers.@nestjs-odata/typeorm:ODataTypeOrmModule.forFeature()items acceptwriteHandlers: anODataWriteHandlersobject or an injectable class withcreate,deepInsert,update(PATCH),replace(PUT) anddelete. They route the entity set's writes, including$batch, through application code instead of the repository. A missing handler answers 405.- Handlers receive the parsed body, the parsed key, and an
ODataWriteContext: entity set, EDM type, operation, raw key,If-Match, NestExecutionContext, request, and in a changeset the transaction'sEntityManagerand the batch info. They return the entity to serialize. - New
etagitem option (a property name or a function) sets the entity set's ETag source. It overrides@ODataETag/@UpdateDateColumn, is sent on by-key reads and handler-written responses, andetagMatches()/formatWeakETag()are exported. - New
ODataTypeOrmModule.forRoot({ changesetRunner })runs$batchchangesets inside the application's own unit of work (or provide the newODATA_CHANGESET_RUNNERtoken). The default is aQueryRunnertransaction exposed to handlers asctx.manager. A runner that wraps errors no longer hides the failing part's status. $batchresponse parts now carry theirLocationandETagheaders, and entity bodies their@odata.etag, for every ETag source (also@ODataETag/@UpdateDateColumn) and on GET by key. Before, part headers were dropped.If-Match: *and ETag lists are accepted for every ETag source.- A handler that returns no entity fails with 500 (HTTP and
$batch); deep inserts whose nested entities belong to a handler-backed entity set are refused with 400;nullnavigation values no longer count as a deep insert. $batchkeeps the status of anHttpExceptionfound in an error'scausechain.- Scoped writes only take a row lock inside a transaction (PostgreSQL refuses
FOR UPDATEoutside one).
@nestjs-odata/core: POST responses whose entity carries an adapter-provided ETag get theETagheader and@odata.etag.TypeOrmETagProvider.validateIfMatch()now uses the same comparison as the write paths (*, lists), andcomputeETag()the same format asformatWeakETag(). NewhasEntityETag()helper.- OData conformance: a 405 from write handlers carries an
Allowheader (Part 1 §9.2.2); repository creates send the entity's ETag and@odata.etag(instead of none);$batchrepository writes checkIf-Matchlike the HTTP routes (412).
Patch Changes
3.0.0
Minor Changes
#35
d204ea2Thanks @cberd1509! - Dependency bumps to the latest safe versions, plus a focused round of fixes and DX improvements surfaced by a real-world multi-entity integration.Bug fixes
@nestjs-odata/typeorm:TypeOrmAutoHandlerno longer mis-routes requests to the first-registered entity whenforFeature([A, B, ...])is called with multiple entities. The handler now resolves the correctRepositoryper request from the entity-set name viaDataSource+EdmRegistry.TypeOrmQueryTranslator.translate()accepts an optional per-request repo override (backwards compatible for single-entity callers). Eliminates the downstream "column does not exist" 500 that hit any filter referencing a column unique to the second-registered entity.
New features / DX improvements
@nestjs-odata/typeorm:ODataTypeOrmModule.forFeature()now accepts a mixed array of entity classes and{ entity, name }config objects so you can override the OData entity-set name without touching the entity class. Avoids the/odata/UserEntitiesugliness that comes from theEntitysuffix convention — pass{ entity: UserEntity, name: 'Users' }to expose/odata/Usersinstead. Override wins over@ODataEntitySetdecorator and default pluralization.@nestjs-odata/typeorm:forFeature()accepts a newoptions.controllersarray. When provided, controllers are both PATH_METADATA-patched withserviceRootAND registered in the dynamic module — eliminating the "declare in two places" papercut (ODataModule .forRoot({controllers})+@Module({controllers})). Single declaration inforFeatureis now sufficient for DI resolution.@nestjs-odata/typeorm:@odata.nextLinkis now built from `serviceRoot- entitySetName
(notreq.originalUrl), so it's prefix-consistent with@odata.contextand@odata.id. OData v4 clients (Excel, Olingo, odata2ts) can now navigate paginated responses when the app is mounted under a NestsetGlobalPrefix`.
- entitySetName
@nestjs-odata/core: NewODataModule.globalPrefixExclude(serviceRoot?)static helper returning the Express 5 splat-style exclude patterns forapp.setGlobalPrefix(). Replaces hand-crafted'api/odata{/*splat}'snippets — callapp.setGlobalPrefix('api', { exclude: ODataModule .globalPrefixExclude() }).
Tests
- New e2e regression suite
apps/test-app/test/multi-entity-disambiguation .e2e-spec.ts(16 tests) covering: multi-entity routing for list / get-by-key / $count / POST / PATCH / DELETE / multi-word$filterliteral / entity registration-order swap, the{ entity, name }override, the single-declarationforFeature({ controllers })pattern, the prefix- consistent@odata.nextLink, and theglobalPrefixExcludehelper.
Docs
docs/guide/getting-started.md: new sections on multi-entity registration- custom set names, and
setGlobalPrefix()integration.
- custom set names, and
docs/guide/configuration.md: documents the{ entity, name }form, thecontrollersoption onforFeature, and the global-prefix workflow.docs/api/module.md: full reference forODataModule.globalPrefixExclude()and the expandedODataTypeOrmModule.forFeature()signature including the newODataTypeOrmFeatureItemtype.docs/guide/troubleshooting.md: three new entries for the common gotchas (double-prefixed routes, uglyEntitiesURL suffix, multi-entity wrong- row symptom).
Backwards compatibility
All changes are additive. Existing
forFeature([Product, Order])calls andforRoot({ controllers })+@Module({ controllers })setups continue to work unchanged. The test-app's existing 197 e2e tests pass without modification.
Patch Changes
- Updated dependencies [
d204ea2]:- @nestjs-odata/core@2.1.0
2.0.0
Major Changes
0966a8cThanks @cberd1509! - Initial v1.0.0 release — OData v4 for NestJS with TypeORM integrationFeatures:
- Auto-derive OData EDM from TypeORM entities (zero double-declaration)
- Full query surface: $filter, $select, $orderby, $top, $skip, $count, $expand
- Filter functions: string, date/time, arithmetic, lambda (any/all)
- CRUD operations with PATCH, PUT (full replace), and deep inserts
- $batch with multipart/mixed and Content-ID cross-references
- $search with pluggable search providers
- $apply aggregation pipelines (groupby, aggregate, filter, compute)
- Response annotations (@odata.id, @odata.type, @odata.etag)
- ETag-based optimistic concurrency control
- Configurable security limits and validation
- $metadata endpoint with CSDL XML
- Zero-boilerplate module API (forRoot/forFeature)
Patch Changes
- Updated dependencies [
0966a8c]:- @nestjs-odata/core@2.0.0