docs: test assignment description and design decisions

This commit is contained in:
arswarog committed 2026-11-18 10:00:15 +03:00
1 parent 18e4a97691
commit 2dc01cc886
1 file changed
+98 -88
+98 -88
View File
@@ -1,126 +1,136 @@
<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>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
Требуемые сущности:
## Description
```mermaid
erDiagram
Profile ||--o{ Skill : Навыки
Profile ||--o{ Link : Ссылки
Profile ||--o{ Experience : "Опыт работы"
Profile ||--o{ Project : "Проекты"
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
Profile {
string firstName "имя"
string lastName "фамилия"
string description "краткое описание"
}
## Project setup
Link {
string name "название"
string link "адрес ссылки"
}
```bash
$ yarn install
Skill {
string name "название навыка"
}
Project {
string name "название проекта"
string link "адрес проекта или его репозитория"
string description "описание"
}
Experience {
string company "компания"
string position "должность"
string period "период работы"
string[] achievements "достижения"
}
```
## Compile and run the project
### Требования:
```bash
# development
$ yarn run start
- Автоподготовка базы данных
- Автозаполнение данных при старте
- Доступ по GraphQL
# watch mode
$ yarn run start:dev
> Требуется уточнить, что бизнес имеет в виду под подготовкой базы данных
# production mode
$ yarn run start:prod
```
### Неявные требования
## Run tests
Особых неявных требований нет
```bash
# unit tests
$ yarn run test
## Решения
# e2e tests
$ yarn run test:e2e
### База данных
# test coverage
$ yarn run test:cov
```
Конечно, в данном ТЗ данных столько, что достаточно было бы одного JSON файла, но возьмем БД postgres
## Deployment
Postgres - популярная, широкий функционал. Уже есть инфраструктура для нее.
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.
Другие варианты:
- MariaDB - достаточно широкий функционал. Нет под нее инфраструктуры.
- SQLite - небольшая, встраиваемая. Инфраструктуры не требуется
- MongoDB - документная, что тоже подходит. Нет под нее инфраструктуры.
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
$ yarn 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.
**Создание БД:**
- локально: вручную созданная БД
- на "проде" использую уже имеющуюся у меня инфраструктуру: БД будет создаваться скриптом на сервере
## Observability
**Миграции:**
In production applications, observability is essential for understanding how your system behaves, detecting issues early, and maintaining reliable performance.
Так как миграция работает с бизнес-данными (а данные терять и повреждать нельзя), то накатывание миграций должно быть
достаточно явным процессом, и сама миграция должна быть однозначной.
[NestJS Observe](https://observe.nestjs.com) automatically instruments your NestJS application, giving you deep visibility into your system with minimal setup:
Потому просто дать команду "приведи БД в соответствие со схемой" в orm библиотеке небезопасно, требуется именно миграция.
- **Distributed tracing:** Follow requests across services and understand how they flow through your system.
- **Waterfall analysis:** Visualize request execution and identify slow operations, bottlenecks, and unexpected delays.
- **Performance analysis:** Analyze application performance in real time and quickly pinpoint areas that need optimization.
- **Metrics:** Track key application and infrastructure metrics to understand system health and performance trends.
- **Logging:** Centralize and correlate logs with traces and other telemetry to make debugging easier.
- **Error tracking:** Detect errors quickly and investigate their root causes with the surrounding context.
- **SLA monitoring:** Track service-level objectives and identify when your application is approaching or exceeding defined thresholds.
- **Alarms and alerts:** Set up alerts for critical errors, performance degradation, SLA violations, and other anomalies so your team can react quickly.
Подходящим считаю накатывать миграцию перед публикацией новой версии приложения прямо в CI.
This project is already instrumented. To connect it, run this and approve the code it prints at [observe.nestjs.com/link](https://observe.nestjs.com/link) - signing up for free if you have no account:
### Автозаполнение данных на старте
```bash
$ npx @nestjs/observe link
```
На старте приложения, проверить количество записей в таблицах, и там, где пусто, заполнить данными из кода или JSON.
It writes the app key and secret into `.env` and makes every `nest start` script (`start`, `start:dev`, `start:debug`) load it. In production, set `OBSERVE_APP_KEY` and `OBSERVE_APP_SECRET` in the environment instead.
В реальном приложении это надо обсудить, а здесь достаточно такого решения.
Or do it by hand: create an application and an API key at [observe.nestjs.com](https://observe.nestjs.com), and set the pair as `OBSERVE_APP_KEY` and `OBSERVE_APP_SECRET` in the environment the app runs in.
### Остальное
The free plan needs no payment details and covers 300,000 events a month. You can also browse the [live demo](https://www.observe-demo.nestjs.com/dashboard) first - the whole dashboard over a busy service's data, with nothing to install.
- Выделенного фронта нет, есть Apollo Playground, который доступен из библиотек.
## 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.
- Auto-instrument your application with [NestJS Observe](https://observe.nestjs.com). Distributed tracing, metrics, and logging made easy. Error tracking and performance monitoring for your NestJS applications.
- 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).
Вот кейс по проектированию [биллинга](https://portfolio.arswarog.ru/cases/billing), где разделение ответственности
дает преимущества.
## 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
- Resolver: Точки входа, права доступа. Без бизнес логики
- Service: Бизнес логика
- Data Access Layer: Проектно специфичные методы для доступа к данным. Бизнес логика присутствует, только если она нужна
на уровне БД
- Repository: API библиотеки БД
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
В данном случае Data Access Layer будет явно излишним.
Так же эти слои показывают направление связей:
- Resolver имеет доступ только к Service
- Service имеет доступ только к Repository
### Сущности
Идентификаторы сущностям на уровне API не нужны, поэтому в GraphQL они не отдаются. Внутри БД они есть:
Prisma требует у модели уникальный идентификатор, и `id` (autoincrement) заодно даёт стабильные
связи `profileId` и порядок выдачи. Наружу это не протекает — DTO описывает только бизнес-поля.
Профиль ровно один, но запись профиля оставлю: так вложенность (профиль → навыки/ссылки/опыт/проекты)
выражена отношением в БД, а не соглашением «все строки таблицы принадлежат профилю».
## GraphQL
Разделил на отдельные ресолверы для разделения ответственности