1.3.0 • Published 10 months ago

@tamnt-work/nuxt-mapper v1.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

@tamnt-work/nuxt-mapper

npm version npm downloads License Nuxt

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 definition
  • mappers/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: boolean
  • min: number (min length)
  • max: number (max length)
  • email: boolean
  • regex: string
  • url: boolean
  • uuid: boolean
  • cuid: boolean
  • length: number
  • startsWith: string
  • endsWith: string
  • includes: 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: boolean
  • positive: boolean
  • negative: boolean
  • multipleOf: number
  • finite: boolean
  • safe: boolean

Array Validations

  • type: array
  • nonempty: boolean
  • min_items: number
  • max_items: number
  • item: 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

License

MIT License

1.3.0

10 months ago

1.2.4

10 months ago

1.2.3

10 months ago

1.2.2

10 months ago

1.2.1

10 months ago

1.2.0

10 months ago

1.1.0

10 months ago