# Migration Guide: 11.3.x → 11.4.x

## TL;DR

**Not using `@nodepit/migrate-state-store-mongodb`?**
```bash
npm install @lenne.tech/nest-server@11.4.x
npm run build && npm test  # Done! No breaking changes.
```

**Using `@nodepit/migrate-state-store-mongodb`?** Follow the migration steps below to switch to the built-in system.

---

## Overview

| Category | Details |
|----------|---------|
| **Breaking Changes** | None (backward compatible) |
| **New Features** | Built-in migration CLI, MongoStateStore, helper functions |
| **Bugfixes** | Various MapAndValidatePipe improvements (11.4.2-11.4.5) |
| **Migration Effort** | ~5 min (no @nodepit) / ~15 min (with @nodepit migration) |

---

## Prerequisites

### ts-node (Required for TypeScript migrations)

```bash
npm install --save-dev ts-node
```

---

## What's New in 11.4.x

### 1. Built-in Migration CLI

No external `migrate` package required - CLI included in nest-server:

```bash
npx migrate --help
```

### 2. Migration Helper Functions

```typescript
import { getDb, uploadFileToGridFS, createMigrationStore } from '@lenne.tech/nest-server';

const db = await getDb('mongodb://localhost/mydb');
const fileId = await uploadFileToGridFS('mongodb://localhost/mydb', './assets/logo.png');
```

### 3. MongoStateStore

Drop-in replacement for `@nodepit/migrate-state-store-mongodb` with MongoDB 7.x support and cluster locking.

### 4. S_VERIFIED System Role (11.4.8)

New system role for checking user verification status:

```typescript
@Roles(RoleEnum.S_VERIFIED)  // Requires verified user
async someMethod() { }
```

Checks: `user.verified || user.verifiedAt || user.emailVerified`

---

## Migration from @nodepit

### Step 1: Remove Old Packages

```bash
npm uninstall migrate @nodepit/migrate-state-store-mongodb ts-migrate-mongoose
```

### Step 2: Update nest-server

```bash
npm install @lenne.tech/nest-server@11.4.x
```

### Step 3: Update `migrations-utils/migrate.js`

**Before:**
```javascript
import config from '../src/config.env';
const { MongoStateStore } = require('@nodepit/migrate-state-store-mongodb');

module.exports = class MyMongoStateStore extends MongoStateStore {
  constructor() {
    super({ uri: config.mongoose.uri, collectionName: 'migrations' });
  }
};
```

**After:**
```javascript
const { createMigrationStore } = require('@lenne.tech/nest-server');
const config = require('../src/config.env');

module.exports = createMigrationStore(
  config.default.mongoose.uri,
  'migrations'
);
```

### Step 4: Update `migrations-utils/db.ts`

**Before:**
```typescript
import { GridFSBucket, MongoClient, ObjectId } from 'mongodb';
import config from '../src/config.env';

const MONGO_URL = config.mongoose.uri;

export const getDb = async () => {
  const client: MongoClient = await MongoClient.connect(MONGO_URL);
  return client.db();
};

export const uploadFile = async (relativePath, options?) => {
  // ... custom implementation
};
```

**After:**
```typescript
/**
 * Legacy compatibility layer - allows existing migrations to work unchanged
 */
import {
  createMigrationStore,
  getDb as nestServerGetDb,
  uploadFileToGridFS,
} from '@lenne.tech/nest-server';
import config from '../src/config.env';

export { createMigrationStore, uploadFileToGridFS };

// Wrapper: existing migrations call getDb() without parameters
export const getDb = async () => nestServerGetDb(config.mongoose.uri);
```

### Step 5: Delete Obsolete Files

```bash
rm migrations-utils/template.ts migrations-utils/ts-compiler.js
```

### Step 6: Update package.json Scripts

**Key changes:**
- Command (`up`, `down`, `create`) comes **first**, then options
- Use nest-server paths for template and compiler

```json
{
  "scripts": {
    "migrate:create": "f() { migrate create \"$1\" --template-file ./node_modules/@lenne.tech/nest-server/dist/core/modules/migrate/templates/migration-project.template.ts --migrations-dir ./migrations --compiler ts:./node_modules/@lenne.tech/nest-server/dist/core/modules/migrate/helpers/ts-compiler.js; }; f",
    "migrate:up": "migrate up --store ./migrations-utils/migrate.js --migrations-dir ./migrations --compiler ts:./node_modules/@lenne.tech/nest-server/dist/core/modules/migrate/helpers/ts-compiler.js",
    "migrate:down": "migrate down --store ./migrations-utils/migrate.js --migrations-dir ./migrations --compiler ts:./node_modules/@lenne.tech/nest-server/dist/core/modules/migrate/helpers/ts-compiler.js",
    "migrate:list": "migrate list --store ./migrations-utils/migrate.js --migrations-dir ./migrations --compiler ts:./node_modules/@lenne.tech/nest-server/dist/core/modules/migrate/helpers/ts-compiler.js"
  }
}
```

**Environment-specific scripts (optional):**
```json
{
  "migrate:develop:up": "NODE_ENV=develop migrate up --store ./migrations-utils/migrate.js --migrations-dir ./migrations --compiler ts:./node_modules/@lenne.tech/nest-server/dist/core/modules/migrate/helpers/ts-compiler.js",
  "migrate:prod:up": "NODE_ENV=production migrate up --store ./migrations-utils/migrate.js --migrations-dir ./migrations --compiler ts:./node_modules/@lenne.tech/nest-server/dist/core/modules/migrate/helpers/ts-compiler.js"
}
```

### Step 7: Verify

```bash
npm install
npm run migrate:list        # Should show existing migrations
npm run migrate:create test # Should create new migration
rm migrations/*-test.ts     # Clean up
npm run build && npm test
```

---

## Compatibility Notes

| What | Status |
|------|--------|
| Existing migration files | ✅ Unchanged |
| Migration state in MongoDB | ✅ Same format, no data loss |
| Projects without @nodepit | ✅ No action needed |

---

## Troubleshooting

| Issue | Solution |
|-------|----------|
| `migrate` command not found | Use `npx migrate` or ensure nest-server is installed |
| `ts-node is required` | `npm install --save-dev ts-node` |
| `Cannot find module '../src/config.env'` | Use `require('../src/config.env')` and access `config.default.mongoose.uri` |
| Migrations run on multiple nodes | Add lock collection: `createMigrationStore(uri, 'migrations', 'migration_lock')` |

---

## File Structure After Migration

```
migrations-utils/
├── migrate.js    # Required (7 lines) - uses createMigrationStore
└── db.ts         # Optional (5 lines) - compatibility wrapper for old migrations
```

**Deleted:** `template.ts`, `ts-compiler.js` (now provided by nest-server)

---

## Module Documentation

- **README:** [src/core/modules/migrate/README.md](../src/core/modules/migrate/README.md)
- **@nodepit Migration:** [src/core/modules/migrate/MIGRATION_FROM_NODEPIT.md](../src/core/modules/migrate/MIGRATION_FROM_NODEPIT.md)

---

## References

- [nest-server-starter](https://github.com/lenneTech/nest-server-starter) (reference implementation)
