@tamnt-work/nuxt-mapper v1.3.0
@tamnt-work/nuxt-mapper
A powerful data mapper and converter module for Nuxt 3 that helps you transform data between different formats from backend to frontend using schema definitions.
Features
- š Schema-driven development
- š Automatic model and DTO generation
- š Type-safe data transformations
- š Real-time schema watching
- š CLI tools for code generation
- ā”ļø Hot reload support
- ⨠Zod-powered request validation
- š i18n support for validation messages
Installation
# Using package manager of choice
pnpm add @tamnt-work/nuxt-mapper
yarn add @tamnt-work/nuxt-mapper
npm install @tamnt-work/nuxt-mapper
bun add @tamnt-work/nuxt-mapper
# Optional: Install zod if using request validation
pnpm add zod
yarn add zod
npm install zod
bun add zod
Setup
Add to your nuxt.config.ts
:
export default defineNuxtConfig({
modules: ['@tamnt-work/nuxt-mapper'],
dataMapper: {
// Enable watch mode in development
watch: true,
// Enable ESLint auto-fix for generated files
fixEslint: true,
// Custom mappers directory (default: './mappers')
mappersDir: './mappers',
// Add services directory to auto-imports
imports: {
dirs: ['services']
}
}
})
Usage
1. Model Schema Definition
First, initialize the schema files using the CLI:
# Initialize model schema
npx tw mapper init
# Initialize request schema
npx tw request init
This will create the following files:
mappers/schema.tw
: Model schema definitionmappers/request.tw
: Request validation schema
Then modify the schema files according to your needs:
# User Model
User:
type: model
mappings:
id:
type: string
map: id
required: true
name:
type: string
map: fullName
email:
type: string
required: true
address:
type: string
map: address.street
relationships:
posts:
type: Post[]
map: user.posts
# Post Model
Post:
type: model
mappings:
id:
type: string
required: true
title:
type: string
content:
type: string
map: body
relationships:
author:
type: User
map: post.user
2. Request Validation Schema
Create a request.tw
file for API validation rules:
User:
create:
fullName:
required: true
min: 2
max: 100
messages:
required: "Full name is required"
min: "Name must be at least {min} characters"
email:
required: true
email: true
messages:
email: "Please enter a valid email address"
# Array validation example
addresses:
type: array
item:
type: object
properties:
street:
required: true
min: 5
city:
required: true
max_items: 3
messages:
max_items: "Maximum {max} addresses allowed"
update:
id:
required: true
fullName:
min: 2
max: 100
email:
email: true
3. Generated Structure
After running the generators, your directory will look like:
mappers/
āāā schema.tw # Model schema definition
āāā request.tw # Request validation schema
āāā user/
ā āāā user.model.ts # User Plain Model
ā āāā user.dto.ts # User DTO with mapping
ā āāā requests/ # Generated request validators
ā āāā create-user.request.ts
ā āāā update-user.request.ts
ā āāā delete-user.request.ts
āāā post/
āāā post.model.ts
āāā post.dto.ts
āāā requests/
4. CLI Commands
Generate Models & DTOs
# Generate all models
npx tw mapper
# Generate specific models
npx tw mapper -m user,post
# Watch mode
npx tw mapper -w
# Initialize schema
npx tw mapper init
Options:
| Option | Description | Default |
|--------|-------------|---------|
| -m, --models
| Models to generate | All models |
| -w, --watch
| Watch for changes | false
|
| -f, --fix
| Auto-fix ESLint | false
|
| -s, --schema
| Schema file path | ./mappers/schema.tw
|
Generate Request Validators
# Generate all request validators
npx tw request
# Generate for specific models
npx tw request -m user,post
# Watch mode
npx tw request -w
# Initialize request schema
npx tw request init
Options:
| Option | Description | Default |
|--------|-------------|---------|
| -m, --models
| Models to generate | All models |
| -w, --watch
| Watch for changes | false
|
| -f, --fix
| Auto-fix ESLint | false
|
| -s, --schema
| Schema file path | ./mappers/request.tw
|
Generate Services
# Initialize service infrastructure
npx tw service init
# Generate services
npx tw service create -n user,post
Options:
| Option | Description | Default |
|--------|-------------|---------|
| -n, --name
| Services to generate | Required |
| -o, --output
| Output directory | ./services
|
5. Validation Rules Reference
String Validations
required
: booleanmin
: number (min length)max
: number (max length)email
: booleanregex
: stringurl
: booleanuuid
: booleancuid
: booleanlength
: numberstartsWith
: stringendsWith
: stringincludes
: string
Number Validations
type: number
gt
: number (greater than)gte
: number (greater than or equal)lt
: number (less than)lte
: number (less than or equal)int
: booleanpositive
: booleannegative
: booleanmultipleOf
: numberfinite
: booleansafe
: boolean
Array Validations
type: array
nonempty
: booleanmin_items
: numbermax_items
: numberitem
: object (nested validation)
Object Validations
type: object
properties
: Record<string, ValidationRule>
Custom Messages
fieldName:
required: true
min: 2
messages:
required: "Custom required message"
min: "Must be at least {min} chars"
i18n Support
fieldName:
required: true
i18n:
required: "validation.field.required"
6. Using Services
// Auto-imported service
const userService = useUserService()
// Create with request validation
const { data: newUser } = await userService.create({
fullName: 'John Doe',
email: 'john@example.com'
} satisfies CreateUserRequest) // Type-safe request validation
// Update with request validation
const { data: updated } = await userService.update('1', {
fullName: 'John Smith'
} satisfies UpdateUserRequest)
// With custom options and request validation
const { data } = await userService.all({
query: { role: 'admin' } satisfies GetUsersRequest
})
// Error handling with Zod validation
try {
const { data } = await userService.create({
// Invalid data
email: 'invalid-email'
} satisfies CreateUserRequest)
} catch (error) {
if (error instanceof z.ZodError) {
// Type-safe validation errors
console.log(error.errors)
}
}
Contributing
# Install dependencies
npm install
# Generate type stubs
npm run dev:prepare
# Development
npm run dev
# Build
npm run dev:build
# Run ESLint
npm run lint
# Run Tests
npm run test
npm run test:watch
# Release
npm run release