docs: test assignment description and design decisions

This commit is contained in:
arswarog committed 2026-11-16 17:30:51 +03:00
1 parent 18e4a97691
commit fadb237229
1 file changed
+197 -109
+197 -109
View File
@@ -1,126 +1,214 @@
<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 Skill {
$ yarn install 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
Особых неявных требований нет
## Решения
### База данных
Конечно, в данном ТЗ данных столько, что достаточно было бы одного JSON файла, но возьмем БД postgres
Postgres - популярная, широкий функционал. Уже есть инфраструктура для нее.
Другие варианты:
- MariaDB - достаточно широкий функционал. Нет под нее инфраструктуры.
- SQLite - небольшая, встраиваемая. Инфраструктуры не требуется
- MongoDB - документная, что тоже подходит. Нет под нее инфраструктуры.
### Подготовка БД
Под подготовкой БД я понял создание базы данных и накатывание на нее миграций.
**Создание БД:**
- локально: вручную созданная БД
- на "проде" использую уже имеющуюся у меня инфраструктуру: БД будет создаваться скриптом на сервере
**Миграции:**
Так как миграция работает с бизнес-данными (а данные терять и повреждать нельзя), то накатывание миграций должно быть
достаточно явным процессом, и сама миграция должна быть однозначной.
Потому просто дать команду "приведи БД в соответствие со схемой" в orm библиотеке небезопасно, требуется именно миграция.
Подходящим считаю накатывать миграцию перед публикацией новой версии приложения прямо в CI.
### Автозаполнение данных на старте
На старте приложения, проверить количество записей в таблицах, и там, где пусто, заполнить данными из кода или JSON.
В реальном приложении это надо обсудить, а здесь достаточно такого решения.
### Остальное
- Выделенного фронта нет, есть Apollo Playground, который доступен из библиотек.
## Архитектура
> Если строго смотреть на потребности, то архитектура должна быть самой простой, большинство ее элементов можно
> посчитать переусложнением для такой задачи.
>
> Потому некоторые компоненты могут быть избыточны для текущей задачи, но полезны в реальном проекте.
### Горизонтальное разделение ответственности
Потребности в разделении на несколько модулей нет: один модуль, один ресолвер, нужные сущности.
Вот кейс по проектированию [биллинга](https://portfolio.arswarog.ru/cases/billing), где разделение ответственности
дает преимущества.
### Вертикальное разделение ответственности
Обычно модуль я делю на такие слои:
- Resolver / Controller: Точки входа, права доступа. Без бизнес логики
- Service: Бизнес логика
- Data Access Layer: Проектно специфичные методы для доступа к данным. Бизнес логика присутствует, только если она нужна
на уровне БД
- Repository: API библиотеки БД
В данном случае Data Access Layer будет явно излишним.
Так же эти слои показывают направление связей:
- Resolver имеет доступ только к Service
- Service имеет доступ только к Repository
### Сущности
Идентификаторы сущностям на уровне API не нужны, поэтому в GraphQL они не отдаются. Внутри БД они есть:
Prisma требует у модели уникальный идентификатор, и `id` (autoincrement) заодно даёт стабильные
связи `profileId` и порядок выдачи. Наружу это не протекает — DTO описывает только бизнес-поля.
Профиль ровно один, но запись профиля оставлю: так вложенность (профиль → навыки/ссылки/опыт/проекты)
выражена отношением в БД, а не соглашением «все строки таблицы принадлежат профилю».
---
---
---
## ТЗ
Смысл тестового задания в том, чтобы Вы продемонстрировали навык использования всех перечисленных технологий. Время на выполнение тестового задания не ограничено.
Упор на качество. Убедительная просьба – либо отнеситесь к тестовому заданию серьезно, либо не беритесь за него вовсе.
Создайте Вашу цифровую визитку (backend-приложение), которая презентует Вас как специалиста, с обязательным использованием следующих технологий:
- Git;
- TypeScript;
- Node.js;
- NestJS;
- Prisma;
- GraphQL;
- Docker.
Приложение должно предоставлять Apollo Sandbox, через которое можно получить информацию о Вас, Вашем опыте работы, навыках и проектах.
Бэкенд должен содержать:
1. Профиль:
- имя;
- краткое описание;
- ссылки на GitHub/LinkedIn или другие профессиональные ресурсы.
2. Список навыков.
3. Опыт работы:
- компания;
- должность;
- период работы;
- Ваши достижения.
4. Проекты:
- название;
- ссылка на проект/репозиторий.
При запуске приложения база данных должна быть автоматически подготовлена и заполнена Вашими данными.
API должно позволять получить профиль и связанные с ним данные, например:
```graphql
query {
profile {
name
description
skills {
name
}
experience {
company
position
}
projects {
name
}
}
}
``` ```
## Run tests Конкретную структуру GraphQL API, базы данных и архитектуру приложения выберите самостоятельно. Обоснуйте принятые архитектурные решения в README.md файле.
```bash Бизнес-логика, работа с данными и GraphQL API должны иметь разумное разделение ответственности.
# unit tests
$ yarn run test
# e2e tests Что оценивается:
$ yarn run test:e2e - в первую очередь оценивается не количество написанного кода, а качество инженерных решений.
# test coverage Обратите внимание на:
$ yarn run test:cov - структуру приложения и разделение ответственности;
``` - работу GraphQL с вложенными данными для оптимизации запросов к базе данных;
- взаимодействие с базой данных;
- инициализацию и заполнение базы данных;
- читаемость и поддерживаемость кода;
- корректную работу приложения после запуска с нуля.
## Deployment Просим предоставить:
1. Ссылку на проект (для просмотра). Бэкенд можете попробовать развернуть на Vercel/Render/Railway или любым удобным для Вас способом;
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. 2. Ссылку на Git (для ознакомления с исходным кодом).
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:
- **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.
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
```
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.
## 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).
## 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).