diff --git a/README.md b/README.md index be834f9..1deaafb 100644 --- a/README.md +++ b/README.md @@ -1,126 +1,136 @@ -
+# Тестовое задание -[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 -[circleci-url]: https://circleci.com/gh/nestjs/nest +## Бизнес требования -A progressive Node.js framework for building efficient and scalable server-side applications.
- - +Требуемые сущности: -## Description - -[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. - -## Project setup - -```bash -$ yarn install +```mermaid +erDiagram + Profile ||--o{ Skill : Навыки + Profile ||--o{ Link : Ссылки + Profile ||--o{ Experience : "Опыт работы" + Profile ||--o{ Project : "Проекты" + + Profile { + string firstName "имя" + string lastName "фамилия" + string description "краткое описание" + } + + Link { + string name "название" + string link "адрес ссылки" + } + + 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 +Конечно, в данном ТЗ данных столько, что достаточно было бы одного JSON файла, но возьмем БД postgres -# test coverage -$ yarn run test:cov -``` +Postgres - популярная, широкий функционал. Уже есть инфраструктура для нее. -## Deployment +Другие варианты: +- MariaDB - достаточно широкий функционал. Нет под нее инфраструктуры. +- SQLite - небольшая, встраиваемая. Инфраструктуры не требуется +- MongoDB - документная, что тоже подходит. Нет под нее инфраструктуры. -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 -$ 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. +Потому просто дать команду "приведи БД в соответствие со схемой" в orm библиотеке небезопасно, требуется именно миграция. -[NestJS Observe](https://observe.nestjs.com) automatically instruments your NestJS application, giving you deep visibility into your system with minimal setup: +Подходящим считаю накатывать миграцию перед публикацией новой версии приложения прямо в CI. -- **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: +На старте приложения, проверить количество записей в таблицах, и там, где пусто, заполнить данными из кода или JSON. -```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. +- Выделенного фронта нет, есть Apollo Playground, который доступен из библиотек. -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 +Вот кейс по проектированию [биллинга](https://portfolio.arswarog.ru/cases/billing), где разделение ответственности +дает преимущества. -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) +- Resolver: Точки входа, права доступа. Без бизнес логики +- Service: Бизнес логика +- Data Access Layer: Проектно специфичные методы для доступа к данным. Бизнес логика присутствует, только если она нужна + на уровне БД +- Repository: API библиотеки БД -## License +В данном случае Data Access Layer будет явно излишним. -Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE). +Так же эти слои показывают направление связей: +- Resolver имеет доступ только к Service +- Service имеет доступ только к Repository + +### Сущности + +Идентификаторы сущностям на уровне API не нужны, поэтому в GraphQL они не отдаются. Внутри БД они есть: +Prisma требует у модели уникальный идентификатор, и `id` (autoincrement) заодно даёт стабильные +связи `profileId` и порядок выдачи. Наружу это не протекает — DTO описывает только бизнес-поля. + +Профиль ровно один, но запись профиля оставлю: так вложенность (профиль → навыки/ссылки/опыт/проекты) +выражена отношением в БД, а не соглашением «все строки таблицы принадлежат профилю». + +## GraphQL + +Разделил на отдельные ресолверы для разделения ответственности \ No newline at end of file