Accept and automatically parse NDJSON stream requests in NestJS with Express!
A lightweight library that enables NestJS applications to accept and process streaming NDJSON (Newline Delimited JSON) requests with Express. Perfect for handling large datasets, real-time data feeds, and streaming APIs where each line contains a valid JSON object.
- ✨ Simple decorator-based API for handling NDJSON streams
- 🚀 Memory-efficient processing using AsyncGenerators
- 🎯 TypeScript support with generic types
- 🔧 Configurable batch processing
- 🛡️ Automatic content-type validation
- ⚡ Zero dependencies (only NestJS peer dependencies)
- Node.js >= 20.0.0
- NestJS >= 10.0.0
- Express framework
npm install nest-ndjson-req-stream
import { Controller, Post } from '@nestjs/common';
import { NdJsonStreamReq, NdJsonStreamRequest } from 'nest-ndjson-req-stream';
interface DataItem {
id: number;
name: string;
value: number;
}
@Controller('stream')
export class StreamController {
@Post('process')
async processStream(
@NdJsonStreamReq<DataItem>() request: NdJsonStreamRequest<DataItem>
) {
const results: DataItem[] = [];
// Process each item from the stream
for await (const item of request.body) {
// Process your data here
console.log('Received:', item);
results.push(item);
}
return {
message: 'Stream processed successfully',
itemCount: results.length,
};
}
}
Use TypeScript generics for type-safe stream processing:
interface User {
id: string;
email: string;
profile: {
name: string;
age: number;
};
}
@Post('users')
async importUsers(
@NdJsonStreamReq() request: NdJsonStreamRequest<User>
) {
for await (const user of request.body) {
// TypeScript knows that user is of type User
console.log(user.email); // ✅ Type safe
console.log(user.profile.name); // ✅ Type safe
}
}
Parameter decorator for handling NDJSON streaming requests.
batchSize?: number
- The batch size for processing streamed objects (default: 25)
Extended Express Request interface with AsyncGenerator type body:
body: AsyncGenerator<T>
- AsyncGenerator that yields parsed NDJSON objectsbatchSize: number
- The configured batch size for processing
# Run unit tests
npm run test
# Run tests with coverage
npm run test:cov
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature
) - Commit your changes (
git commit -m 'Add some AmazingFeature'
) - Push to the branch (
git push origin feature/AmazingFeature
) - Open a Pull Request
This project is MIT licensed.