initial commit
This commit is contained in:
commit
89fc5d680d
56
.gitignore
vendored
Normal file
56
.gitignore
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
# compiled output
|
||||
/dist
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# Tests
|
||||
/coverage
|
||||
/.nyc_output
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# temp directory
|
||||
.temp
|
||||
.tmp
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
4
.prettierrc
Normal file
4
.prettierrc
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
98
README.md
Normal file
98
README.md
Normal file
@ -0,0 +1,98 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
|
||||
## Description
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
|
||||
## Project setup
|
||||
|
||||
```bash
|
||||
$ npm install
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ npm run start
|
||||
|
||||
# watch mode
|
||||
$ npm run start:dev
|
||||
|
||||
# production mode
|
||||
$ npm run start:prod
|
||||
```
|
||||
|
||||
## Run tests
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ npm run test
|
||||
|
||||
# e2e tests
|
||||
$ npm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ npm run test:cov
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
|
||||
```bash
|
||||
$ npm install -g @nestjs/mau
|
||||
$ mau deploy
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
|
||||
## Resources
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
|
||||
## Support
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||
71
docs/api.md
Normal file
71
docs/api.md
Normal file
@ -0,0 +1,71 @@
|
||||
# Form Utility API Documentation
|
||||
|
||||
## Overview
|
||||
This document provides a quick reference for the **Form Utility** backend API endpoints that are intended for consumption by the frontend. All endpoints are prefixed with the base URL of the deployed service (e.g., `https://api.example.com`).
|
||||
|
||||
---
|
||||
|
||||
## Endpoints
|
||||
|
||||
| Method | Path | Description | Request Body | Success Response | Notes |
|
||||
|--------|------|-------------|--------------|------------------|-------|
|
||||
| **POST** | `/form/create-or-update` | Create a new form or update an existing one. If `id` is omitted, a new form is created; otherwise the specified form is updated. | `CreateUpdateDto` (JSON) | `{ "id": "string", "name": "string", "field": { ... } }` | Returns the created/updated form object. |
|
||||
| **GET** | `/form` | Retrieve a list of all forms. | _None_ | `Form[]` (array of form objects) | Pagination is not implemented yet. |
|
||||
| **PATCH** | `/form/:id/fields/:fieldId` | Update a specific field within a form. | `UpdateFieldDto` (JSON) | Updated field object | `:id` – Form identifier, `:fieldId` – Field identifier. |
|
||||
| **DELETE** | `/form/:id/fields/:fieldId` | Delete a specific field from a form. | _None_ | `{ "deleted": true }` | Returns a simple confirmation object. |
|
||||
| **GET** | `/` (root) | Health‑check / greeting endpoint used by the default NestJS scaffold. | _None_ | `"Hello World!"` (string) | Useful for quick service availability checks. |
|
||||
|
||||
---
|
||||
|
||||
## DTO Schemas (TypeScript Interfaces)
|
||||
|
||||
### `CreateUpdateDto`
|
||||
```ts
|
||||
export class CreateUpdateDto {
|
||||
/** Form ID — omit to create a new form */
|
||||
id?: string;
|
||||
|
||||
/** Human‑readable name of the form */
|
||||
name?: string;
|
||||
|
||||
/** Optional initial field definition */
|
||||
field?: CreateFieldDto;
|
||||
}
|
||||
```
|
||||
|
||||
### `UpdateFieldDto`
|
||||
```ts
|
||||
export class UpdateFieldDto {
|
||||
/** New label for the field */
|
||||
label?: string;
|
||||
|
||||
/** Updated value type (e.g., 'text', 'number') */
|
||||
type?: string;
|
||||
|
||||
/** Validation rules, if any */
|
||||
validation?: Record<string, any>;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Usage Example (Fetch API)
|
||||
```js
|
||||
// Create a new form
|
||||
await fetch('https://api.example.com/form/create-or-update', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Customer Survey' })
|
||||
});
|
||||
|
||||
// Get all forms
|
||||
const forms = await fetch('https://api.example.com/form').then(r => r.json());
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Notes for Frontend Developers
|
||||
- All endpoints return JSON payloads.
|
||||
- No authentication is currently enforced; add JWT headers when the auth layer is enabled.
|
||||
- Errors are returned with standard NestJS error format (`statusCode`, `message`, `error`).
|
||||
- The API follows conventional REST semantics; feel free to extend with pagination or filtering as needed.
|
||||
35
eslint.config.mjs
Normal file
35
eslint.config.mjs
Normal file
@ -0,0 +1,35 @@
|
||||
// @ts-check
|
||||
import eslint from '@eslint/js';
|
||||
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
ignores: ['eslint.config.mjs'],
|
||||
},
|
||||
eslint.configs.recommended,
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
eslintPluginPrettierRecommended,
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.node,
|
||||
...globals.jest,
|
||||
},
|
||||
sourceType: 'commonjs',
|
||||
parserOptions: {
|
||||
projectService: true,
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-floating-promises': 'warn',
|
||||
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||
"prettier/prettier": ["error", { endOfLine: "auto" }],
|
||||
},
|
||||
},
|
||||
);
|
||||
8
nest-cli.json
Normal file
8
nest-cli.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
10144
package-lock.json
generated
Normal file
10144
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
78
package.json
Normal file
78
package.json
Normal file
@ -0,0 +1,78 @@
|
||||
{
|
||||
"name": "form-utility-backend",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "^4.0.3",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/mongoose": "^11.0.4",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@nestjs/swagger": "^11.2.6",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.4",
|
||||
"mongoose": "^9.4.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"uuid": "^13.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@eslint/js": "^9.18.0",
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/supertest": "^7.0.0",
|
||||
"eslint": "^9.18.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.2",
|
||||
"globals": "^17.0.0",
|
||||
"jest": "^30.0.0",
|
||||
"prettier": "^3.4.2",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-loader": "^9.5.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.7.3",
|
||||
"typescript-eslint": "^8.20.0"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
12
src/app.controller.ts
Normal file
12
src/app.controller.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(private readonly appService: AppService) {}
|
||||
|
||||
@Get()
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
}
|
||||
26
src/app.module.ts
Normal file
26
src/app.module.ts
Normal file
@ -0,0 +1,26 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { FormModule } from './form/form.module';
|
||||
import { FormService } from './form/form.service';
|
||||
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }), //access env anywhere
|
||||
|
||||
// connect db
|
||||
MongooseModule.forRootAsync({
|
||||
inject: [ConfigService],
|
||||
useFactory: (configService: ConfigService) => ({
|
||||
uri: configService.get<string>('DB_URI'),
|
||||
}),
|
||||
}),
|
||||
FormModule,
|
||||
],
|
||||
controllers: [AppController,],
|
||||
providers: [AppService],
|
||||
})
|
||||
export class AppModule {}
|
||||
8
src/app.service.ts
Normal file
8
src/app.service.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
43
src/form/dto/create-field.dto.ts
Normal file
43
src/form/dto/create-field.dto.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsArray, IsBoolean, IsEnum, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
import { PARENT_TYPE_KEYS, INPUT_SUB_TYPE_KEYS } from '../types/field.type';
|
||||
import type { ParentKeyType, InputSubType } from '../types/field.type';
|
||||
|
||||
|
||||
export class CreateFieldDto {
|
||||
@ApiProperty({ enum: PARENT_TYPE_KEYS, example: 'select' })
|
||||
@IsEnum(PARENT_TYPE_KEYS)
|
||||
@IsNotEmpty()
|
||||
keyType!: ParentKeyType;
|
||||
|
||||
@ApiPropertyOptional({ enum: INPUT_SUB_TYPE_KEYS, example: 'text' })
|
||||
@IsEnum(INPUT_SUB_TYPE_KEYS)
|
||||
@IsOptional()
|
||||
keySubType?: InputSubType;
|
||||
|
||||
@ApiProperty({ example: 'satisfaction' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
keyName!: string;
|
||||
|
||||
@ApiProperty({ example: 'Satisfaction Level' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
label!: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Select an option' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
placeholder?: string;
|
||||
|
||||
@ApiPropertyOptional({ type: [String], example: ['Very Satisfied', 'Satisfied'] })
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@IsOptional()
|
||||
options?: string[];
|
||||
|
||||
@ApiProperty({ example: false })
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
required?: boolean;
|
||||
}
|
||||
22
src/form/dto/create-update.dto.ts
Normal file
22
src/form/dto/create-update.dto.ts
Normal file
@ -0,0 +1,22 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsOptional, IsString, ValidateNested } from "class-validator";
|
||||
import { CreateFieldDto } from "./create-field.dto";
|
||||
import { Type } from "class-transformer";
|
||||
|
||||
export class CreateUpdateDto {
|
||||
@ApiPropertyOptional({ example: '550e8400-uuid', description: 'Form ID — omit to create a new form' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
id?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Customer Feedback Survey' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
name?: string;
|
||||
|
||||
@ApiPropertyOptional({ type: CreateFieldDto })
|
||||
@ValidateNested()
|
||||
@Type(() => CreateFieldDto)
|
||||
@IsOptional()
|
||||
field?: CreateFieldDto;
|
||||
}
|
||||
4
src/form/dto/update-field.dto.ts
Normal file
4
src/form/dto/update-field.dto.ts
Normal file
@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateFieldDto } from './create-field.dto';
|
||||
|
||||
export class UpdateFieldDto extends PartialType(CreateFieldDto) {}
|
||||
46
src/form/form.controller.ts
Normal file
46
src/form/form.controller.ts
Normal file
@ -0,0 +1,46 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Patch,
|
||||
Param,
|
||||
Delete,
|
||||
} from '@nestjs/common';
|
||||
import { FormService } from './form.service';
|
||||
import { ApiOperation } from '@nestjs/swagger';
|
||||
import { UpdateFieldDto } from './dto/update-field.dto';
|
||||
import { CreateUpdateDto } from './dto/create-update.dto';
|
||||
|
||||
@Controller('form')
|
||||
export class FormController {
|
||||
constructor(private readonly formService: FormService) {}
|
||||
|
||||
@Post('create-or-update')
|
||||
@ApiOperation({ summary: 'Create Empty Form, Add Field to form' })
|
||||
async createOne(@Body() createUpdatedDto: CreateUpdateDto) {
|
||||
return await this.formService.createOrUpdate(createUpdatedDto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Find all forms' })
|
||||
async findAll() {
|
||||
return await this.formService.findAll();
|
||||
}
|
||||
|
||||
@Patch(':id/fields/:fieldId')
|
||||
@ApiOperation({ summary: 'update a field in a form' })
|
||||
async updateField(
|
||||
@Param('id') id: string,
|
||||
@Param('fieldId') fieldId: string,
|
||||
@Body() updateFieldDto: UpdateFieldDto,
|
||||
) {
|
||||
return await this.formService.updateField(id, fieldId, updateFieldDto);
|
||||
}
|
||||
|
||||
@Delete(':id/fields/:fieldId')
|
||||
@ApiOperation({ summary: 'Delete a field' })
|
||||
deleteField(@Param('id') id: string, @Param('fieldId') fieldId: string) {
|
||||
return this.formService.deleteField(id, fieldId);
|
||||
}
|
||||
}
|
||||
18
src/form/form.module.ts
Normal file
18
src/form/form.module.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { FormService } from './form.service';
|
||||
import { FormController } from './form.controller';
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { Form, FormSchema } from './schemas/form.schema';
|
||||
import { Field, FieldSchema } from './schemas/field.schema';
|
||||
|
||||
@Module({
|
||||
imports:[
|
||||
MongooseModule.forFeature([
|
||||
{name:Form.name,schema:FormSchema},
|
||||
{name:Field.name, schema:FieldSchema}
|
||||
])
|
||||
],
|
||||
controllers: [FormController],
|
||||
providers: [FormService],
|
||||
})
|
||||
export class FormModule {}
|
||||
80
src/form/form.service.ts
Normal file
80
src/form/form.service.ts
Normal file
@ -0,0 +1,80 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Form, FormDocument, Status } from './schemas/form.schema';
|
||||
import { Model } from 'mongoose';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { CreateFieldDto } from './dto/create-field.dto';
|
||||
import { UpdateFieldDto } from './dto/update-field.dto';
|
||||
import { CreateUpdateDto } from './dto/create-update.dto';
|
||||
|
||||
@Injectable()
|
||||
export class FormService {
|
||||
constructor(@InjectModel(Form.name) private formModel: Model<FormDocument>) {}
|
||||
|
||||
async createOrUpdate(dto: CreateUpdateDto): Promise<Form> {
|
||||
if (!dto.id) {
|
||||
return this.formModel.create({
|
||||
id: uuidv4(),
|
||||
name: dto.name ?? 'Untitled Form',
|
||||
});
|
||||
}
|
||||
|
||||
const form = await this.formModel.findOne({ id: dto.id });
|
||||
if (!form) throw new NotFoundException(`Form ${dto.id} not found`);
|
||||
|
||||
if (!dto.field) return form; // nothing to add, return as-is
|
||||
|
||||
const newField = { id: uuidv4(), ...dto.field };
|
||||
|
||||
const updatedForm = await this.formModel.findOneAndUpdate(
|
||||
{ id: dto.id },
|
||||
{ $push: { fields: newField } },
|
||||
{ new: true },
|
||||
);
|
||||
if (!updatedForm) throw new NotFoundException(`Form ${dto.id} not found`);
|
||||
return form;
|
||||
}
|
||||
|
||||
async findAll(): Promise<Form[]> {
|
||||
return await this.formModel.find().exec();
|
||||
}
|
||||
|
||||
async find(formId: string): Promise<Form> {
|
||||
const form = await this.formModel.findOne({ id: formId }).exec();
|
||||
if (!form) throw new NotFoundException(`Form ${formId} not found`);
|
||||
return form;
|
||||
}
|
||||
|
||||
async updateField(
|
||||
formId: string,
|
||||
fieldId: string,
|
||||
updateFieldDto: UpdateFieldDto,
|
||||
): Promise<Form> {
|
||||
const setPayload = Object.fromEntries(
|
||||
Object.entries(updateFieldDto).map(([k, v]) => [
|
||||
`fields.$[elem].${k}`,
|
||||
v,
|
||||
]),
|
||||
);
|
||||
const form = await this.formModel.findOneAndUpdate(
|
||||
{ id: formId },
|
||||
{ $set: setPayload },
|
||||
{
|
||||
new: true,
|
||||
arrayFilters: [{ 'elem.id': fieldId }],
|
||||
},
|
||||
);
|
||||
if (!form) throw new NotFoundException(`Form ${formId} not found`);
|
||||
return form;
|
||||
}
|
||||
|
||||
async deleteField(formId: string, fieldId: string): Promise<Form> {
|
||||
const form = await this.formModel.findOneAndUpdate(
|
||||
{ id: formId },
|
||||
{ $pull: { fields: { id: fieldId } } },
|
||||
{ new: true },
|
||||
);
|
||||
if (!form) throw new NotFoundException(`Form ${formId} not found`);
|
||||
return form;
|
||||
}
|
||||
}
|
||||
37
src/form/schemas/field.schema.ts
Normal file
37
src/form/schemas/field.schema.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
|
||||
import { Document } from 'mongoose';
|
||||
|
||||
|
||||
import { PARENT_TYPE_KEYS, INPUT_SUB_TYPE_KEYS } from '../types/field.type';
|
||||
import type { ParentKeyType, InputSubType } from '../types/field.type';
|
||||
|
||||
export type FieldDocument = Field & Document;
|
||||
|
||||
@Schema({ timestamps: true })
|
||||
export class Field {
|
||||
@Prop({ required: true, unique:true })
|
||||
id!: string;
|
||||
|
||||
@Prop({ required: true, enum: PARENT_TYPE_KEYS })
|
||||
keyType!: ParentKeyType;
|
||||
|
||||
@Prop({ required: false, enum: INPUT_SUB_TYPE_KEYS })
|
||||
keySubType?: InputSubType;
|
||||
|
||||
@Prop({ required: true })
|
||||
keyName!: string;
|
||||
|
||||
@Prop({ required: true })
|
||||
label!: string;
|
||||
|
||||
@Prop({ required: false })
|
||||
placeholder?: string;
|
||||
|
||||
@Prop({ required: false })
|
||||
options?: string[];
|
||||
|
||||
@Prop({ required: true, default: false })
|
||||
required!: boolean;
|
||||
}
|
||||
|
||||
export const FieldSchema = SchemaFactory.createForClass(Field);
|
||||
30
src/form/schemas/form.schema.ts
Normal file
30
src/form/schemas/form.schema.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
|
||||
import { Document } from 'mongoose';
|
||||
import { Field, FieldSchema } from './field.schema';
|
||||
|
||||
export enum Status {
|
||||
DRAFT = 'draft',
|
||||
SAVED = 'saved',
|
||||
}
|
||||
|
||||
export type FormDocument = Form & Document;
|
||||
@Schema({ timestamps: true })
|
||||
export class Form {
|
||||
@Prop({ required: true, unique: true })
|
||||
id!: string;
|
||||
|
||||
@Prop({ required: true })
|
||||
name!: string;
|
||||
|
||||
@Prop({ type: [FieldSchema], required: false })
|
||||
fields?: Field[];
|
||||
|
||||
@Prop({
|
||||
type: String,
|
||||
enum: Status,
|
||||
default: Status.DRAFT,
|
||||
})
|
||||
status!: Status;
|
||||
}
|
||||
|
||||
export const FormSchema = SchemaFactory.createForClass(Form);
|
||||
62
src/form/types/field.type.ts
Normal file
62
src/form/types/field.type.ts
Normal file
@ -0,0 +1,62 @@
|
||||
// ─── Field Type Definitions ───
|
||||
|
||||
export interface FormField {
|
||||
id: string;
|
||||
keyType: string;
|
||||
keySubType?: string;
|
||||
keyName: string;
|
||||
label: string;
|
||||
placeholder: string;
|
||||
options?: string[];
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export interface FormData {
|
||||
id: string;
|
||||
name: string;
|
||||
fields: FormField[];
|
||||
createdAt: string;
|
||||
generatedCode?: string;
|
||||
}
|
||||
|
||||
// ─── Parent types ───
|
||||
export type ParentKeyType = "input" | "textarea" | "select" | "multiselect" | "checkbox";
|
||||
|
||||
// ─── Child types (only for "input") ───
|
||||
export type InputSubType = "text" | "email" | "number" | "password";
|
||||
|
||||
// ─── Constant lookup tables ───
|
||||
|
||||
export const PARENT_TYPE_LABELS: Readonly<Record<ParentKeyType, string>> = {
|
||||
input: "Input",
|
||||
textarea: "Textarea",
|
||||
select: "Select",
|
||||
multiselect: "Multiselect",
|
||||
checkbox: "Checkbox",
|
||||
} as const;
|
||||
|
||||
export const INPUT_SUB_TYPE_LABELS: Readonly<Record<InputSubType, string>> = {
|
||||
text: "Text",
|
||||
number: "Number",
|
||||
email: "Email",
|
||||
password: "Password",
|
||||
} as const;
|
||||
|
||||
export const PARENT_TYPE_KEYS = Object.keys(PARENT_TYPE_LABELS) as ParentKeyType[];
|
||||
export const INPUT_SUB_TYPE_KEYS = Object.keys(INPUT_SUB_TYPE_LABELS) as InputSubType[];
|
||||
|
||||
// Types that need an options list
|
||||
export const NEEDS_OPTIONS: readonly ParentKeyType[] = ["select", "multiselect", "checkbox"] as const;
|
||||
|
||||
// ─── Derived helpers ───
|
||||
|
||||
export function getFieldTypeLabel(field: FormField): string {
|
||||
const parentLabel = PARENT_TYPE_LABELS[field.keyType as ParentKeyType] ?? field.keyType;
|
||||
|
||||
if (field.keyType === "input" && field.keySubType) {
|
||||
const subLabel = INPUT_SUB_TYPE_LABELS[field.keySubType as InputSubType] ?? field.keySubType;
|
||||
return `${parentLabel} › ${subLabel}`;
|
||||
}
|
||||
|
||||
return parentLabel;
|
||||
}
|
||||
30
src/main.ts
Normal file
30
src/main.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist:true, // strips unknown properties from @Body()
|
||||
forbidNonWhitelisted:true, // throws 400 if unknown props are sent
|
||||
transform:true // converts query string numbers/booleans from strings → correct types
|
||||
})
|
||||
)
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('Form Utility')
|
||||
.setDescription('Form utility api')
|
||||
.setVersion('1.0')
|
||||
.build();
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('api', app, document);
|
||||
|
||||
const configService=app.get(ConfigService)
|
||||
const port=configService.get<number>('PORT')|| 3000;
|
||||
|
||||
await app.listen(port);
|
||||
|
||||
}
|
||||
bootstrap();
|
||||
29
test/app.e2e-spec.ts
Normal file
29
test/app.e2e-spec.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { App } from 'supertest/types';
|
||||
import { AppModule } from './../src/app.module';
|
||||
|
||||
describe('AppController (e2e)', () => {
|
||||
let app: INestApplication<App>;
|
||||
|
||||
beforeEach(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
|
||||
it('/ (GET)', () => {
|
||||
return request(app.getHttpServer())
|
||||
.get('/')
|
||||
.expect(200)
|
||||
.expect('Hello World!');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
9
test/jest-e2e.json
Normal file
9
test/jest-e2e.json
Normal file
@ -0,0 +1,9 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
||||
4
tsconfig.build.json
Normal file
4
tsconfig.build.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
||||
25
tsconfig.json
Normal file
25
tsconfig.json
Normal file
@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "nodenext",
|
||||
"moduleResolution": "nodenext",
|
||||
"resolvePackageJsonExports": true,
|
||||
"esModuleInterop": true,
|
||||
"isolatedModules": true,
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2023",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noImplicitAny": false,
|
||||
"strictBindCallApply": false,
|
||||
"noFallthroughCasesInSwitch": false
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user