profile: dto, prisma access, resolver with dataloaders
- PrismaModule/PrismaService на pg-адаптере (Prisma 7 без движка запросов) - DTO профиля и связей; служебные id/profileId не публикуются в GraphQL - ProfileService — единственное место запросов к БД - DataLoader'ы на каждый запрос: 1 SQL на профиль + по 1 на затронутую связь - GraphQLModule.forRootAsync кладёт лоадеры в контекст - клиент Prisma генерируется в src/, иначе сборка с rootDir src не видит его - DATABASE_URL для api-контейнера собирается в docker-compose
This commit is contained in:
1 parent
bc135b8811
commit
bc98a41614
25 files changed
+386
-32
No files matched your search
+1
-1
@@ -59,4 +59,4 @@ pids
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
/generated/prisma
|
||||
/src/generated
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"ignorePatterns": ["src/generated"],
|
||||
"rules": {
|
||||
"typescript/no-explicit-any": "off",
|
||||
"typescript/no-floating-promises": "error"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
dist
|
||||
coverage
|
||||
src/generated
|
||||
*.d.ts
|
||||
node_modules
|
||||
.obsidian
|
||||
|
||||
@@ -19,6 +19,7 @@ services:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-}
|
||||
POSTGRES_HOST: ${POSTGRES_HOST:-}
|
||||
POSTGRES_PORT: ${POSTGRES_PORT:-5432}
|
||||
DATABASE_URL: postgres://${POSTGRES_USER:-}:${POSTGRES_PASSWORD:-}@${POSTGRES_HOST:-}:${POSTGRES_PORT:-5432}/${POSTGRES_DB:-}
|
||||
labels:
|
||||
caddy: ${BRANCH}.it-smi.jt4d.ru.net
|
||||
caddy.reverse_proxy: '{{upstreams 5000}}'
|
||||
|
||||
+2
-1
@@ -8,7 +8,7 @@
|
||||
"type": "module",
|
||||
"packageManager": "yarn@4.18.0",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"build": "prisma generate && nest build",
|
||||
"deploy": "nest deploy",
|
||||
"format": "prettier --write \"src/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
@@ -32,6 +32,7 @@
|
||||
"@nestjs/platform-express": "^12.0.1",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"dataloader": "^2.2.3",
|
||||
"dotenv": "^18.0.10",
|
||||
"graphql": "^17.1.0",
|
||||
"pg": "^8.23.1",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client"
|
||||
output = "../generated/prisma"
|
||||
output = "../src/generated/prisma"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
|
||||
+16
-9
@@ -7,22 +7,29 @@ import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin
|
||||
import { AppController } from './app.controller.js';
|
||||
import { AppService } from './app.service.js';
|
||||
import { ProfileModule } from './profile/profile.module.js';
|
||||
import { createProfileLoaders, GraphQLContext } from './profile/profile.loaders.js';
|
||||
import { ProfileService } from './profile/profile.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
GraphQLModule.forRoot<ApolloDriverConfig>({
|
||||
GraphQLModule.forRootAsync<ApolloDriverConfig>({
|
||||
driver: ApolloDriver,
|
||||
imports: [ProfileModule],
|
||||
inject: [ProfileService],
|
||||
useFactory: (profileService: ProfileService) => ({
|
||||
autoSchemaFile: true,
|
||||
sortSchema: true,
|
||||
|
||||
autoSchemaFile: true,
|
||||
sortSchema: true,
|
||||
definitions: {
|
||||
path: join(process.cwd(), 'src/graphql.ts'),
|
||||
outputAs: 'class',
|
||||
},
|
||||
|
||||
definitions: {
|
||||
path: join(process.cwd(), 'src/graphql.ts'),
|
||||
outputAs: 'class',
|
||||
},
|
||||
playground: false,
|
||||
plugins: [ApolloServerPluginLandingPageLocalDefault()],
|
||||
|
||||
playground: false,
|
||||
plugins: [ApolloServerPluginLandingPageLocalDefault()],
|
||||
context: (): GraphQLContext => ({ loaders: createProfileLoaders(profileService) }),
|
||||
}),
|
||||
}),
|
||||
ProfileModule,
|
||||
],
|
||||
|
||||
+29
-1
@@ -8,13 +8,41 @@
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
|
||||
export class ExperienceDto {
|
||||
achievements: string[];
|
||||
company: string;
|
||||
period: string;
|
||||
position: string;
|
||||
}
|
||||
|
||||
export class LinkDto {
|
||||
link: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export class ProfileDto {
|
||||
description: string;
|
||||
experience: ExperienceDto[];
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
links: LinkDto[];
|
||||
projects: ProjectDto[];
|
||||
skills: SkillDto[];
|
||||
}
|
||||
|
||||
export class ProjectDto {
|
||||
description: string;
|
||||
link: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export abstract class IQuery {
|
||||
abstract profile(): ProfileDto | Promise<ProfileDto>;
|
||||
abstract profile(): Nullable<ProfileDto> | Promise<Nullable<ProfileDto>>;
|
||||
}
|
||||
|
||||
export class SkillDto {
|
||||
name: string;
|
||||
profile: ProfileDto;
|
||||
}
|
||||
|
||||
type Nullable<T> = T | null;
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dotenv/config';
|
||||
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module.js';
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { PrismaService } from './prisma.service.js';
|
||||
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
|
||||
import { PrismaClient } from '../generated/prisma/client.js';
|
||||
|
||||
/**
|
||||
* Единственная точка доступа к БД.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
|
||||
constructor() {
|
||||
super({ adapter: new PrismaPg(process.env.DATABASE_URL ?? '') });
|
||||
}
|
||||
|
||||
async onModuleInit(): Promise<void> {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Field, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
@ObjectType({ description: 'Опыт работы' })
|
||||
export class ExperienceDto {
|
||||
profileId: number;
|
||||
|
||||
@Field(() => String, { description: 'Компания' })
|
||||
company: string;
|
||||
|
||||
@Field(() => String, { description: 'Должность' })
|
||||
position: string;
|
||||
|
||||
@Field(() => String, { description: 'Период работы' })
|
||||
period: string;
|
||||
|
||||
@Field(() => [String], { description: 'Достижения' })
|
||||
achievements: string[];
|
||||
}
|
||||
@@ -1 +1,5 @@
|
||||
export { ExperienceDto } from './experience.dto.js';
|
||||
export { LinkDto } from './link.dto.js';
|
||||
export { ProfileDto } from './profile.dto.js';
|
||||
export { ProjectDto } from './project.dto.js';
|
||||
export { SkillDto } from './skill.dto.js';
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Field, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
@ObjectType({ description: 'Ссылка' })
|
||||
export class LinkDto {
|
||||
profileId: number;
|
||||
|
||||
@Field(() => String, { description: 'Название ресурса' })
|
||||
name: string;
|
||||
|
||||
@Field(() => String, { description: 'Адрес ссылки' })
|
||||
link: string;
|
||||
}
|
||||
@@ -1,10 +1,32 @@
|
||||
import { Field, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
@ObjectType()
|
||||
import { ExperienceDto } from './experience.dto.js';
|
||||
import { LinkDto } from './link.dto.js';
|
||||
import { ProjectDto } from './project.dto.js';
|
||||
import { SkillDto } from './skill.dto.js';
|
||||
|
||||
@ObjectType({ description: 'Профиль и связанные с ним данные' })
|
||||
export class ProfileDto {
|
||||
@Field()
|
||||
id: number;
|
||||
|
||||
@Field(() => String, { description: 'Имя' })
|
||||
firstName: string;
|
||||
|
||||
@Field()
|
||||
@Field(() => String, { description: 'Фамилия' })
|
||||
lastName: string;
|
||||
|
||||
@Field(() => String, { description: 'Краткое описание' })
|
||||
description: string;
|
||||
|
||||
@Field(() => [SkillDto], { description: 'Навыки' })
|
||||
skills?: SkillDto[];
|
||||
|
||||
@Field(() => [LinkDto], { description: 'Ссылки на профессиональные ресурсы' })
|
||||
links?: LinkDto[];
|
||||
|
||||
@Field(() => [ExperienceDto], { description: 'Опыт работы' })
|
||||
experience?: ExperienceDto[];
|
||||
|
||||
@Field(() => [ProjectDto], { description: 'Проекты' })
|
||||
projects?: ProjectDto[];
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Field, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
@ObjectType({ description: 'Проект' })
|
||||
export class ProjectDto {
|
||||
profileId: number;
|
||||
|
||||
@Field(() => String, { description: 'Название проекта' })
|
||||
name: string;
|
||||
|
||||
@Field(() => String, { description: 'Адрес проекта или его репозитория' })
|
||||
link: string;
|
||||
|
||||
@Field(() => String, { description: 'Описание проекта' })
|
||||
description: string;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Field, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
@ObjectType({ description: 'Навык' })
|
||||
export class SkillDto {
|
||||
profileId: number;
|
||||
|
||||
@Field(() => String, { description: 'Название навыка' })
|
||||
name: string;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import DataLoader from 'dataloader';
|
||||
|
||||
import { ExperienceDto, LinkDto, ProfileDto, ProjectDto, SkillDto } from './dto/index.js';
|
||||
import { ProfileService } from './profile.service.js';
|
||||
|
||||
export interface ProfileLoaders {
|
||||
profiles: DataLoader<number, ProfileDto | null>;
|
||||
skills: DataLoader<number, SkillDto[]>;
|
||||
links: DataLoader<number, LinkDto[]>;
|
||||
experience: DataLoader<number, ExperienceDto[]>;
|
||||
projects: DataLoader<number, ProjectDto[]>;
|
||||
}
|
||||
|
||||
export interface GraphQLContext {
|
||||
loaders: ProfileLoaders;
|
||||
}
|
||||
|
||||
function loaderByProfileId<T extends { profileId: number }>(
|
||||
load: (profileIds: number[]) => Promise<T[]>,
|
||||
): DataLoader<number, T[]> {
|
||||
return new DataLoader<number, T[]>(async (profileIds) => {
|
||||
const rows = await load([...profileIds]);
|
||||
const buckets = new Map<number, T[]>(profileIds.map((id) => [id, []]));
|
||||
|
||||
for (const row of rows) {
|
||||
buckets.get(row.profileId)?.push(row);
|
||||
}
|
||||
|
||||
return profileIds.map((id) => buckets.get(id) ?? []);
|
||||
});
|
||||
}
|
||||
|
||||
function loaderById<T extends { id: number }>(
|
||||
load: (ids: number[]) => Promise<T[]>,
|
||||
): DataLoader<number, T | null> {
|
||||
return new DataLoader<number, T | null>(async (ids) => {
|
||||
const rows = await load([...ids]);
|
||||
const byId = new Map(rows.map((row) => [row.id, row]));
|
||||
|
||||
return ids.map((id) => byId.get(id) ?? null);
|
||||
});
|
||||
}
|
||||
|
||||
export function createProfileLoaders(profileService: ProfileService): ProfileLoaders {
|
||||
return {
|
||||
profiles: loaderById((ids) => profileService.getProfiles(ids)),
|
||||
skills: loaderByProfileId((profileIds) => profileService.getSkills(profileIds)),
|
||||
links: loaderByProfileId((profileIds) => profileService.getLinks(profileIds)),
|
||||
experience: loaderByProfileId((profileIds) => profileService.getExperiences(profileIds)),
|
||||
projects: loaderByProfileId((profileIds) => profileService.getProjects(profileIds)),
|
||||
};
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { PrismaModule } from '../prisma/prisma.module.js';
|
||||
import { ProfileResolver, SkillResolver } from './resolvers/index.js';
|
||||
import { ProfileService } from './profile.service.js';
|
||||
import { ProfileResolver } from './profile.resolver.js';
|
||||
|
||||
@Module({
|
||||
providers: [ProfileService, ProfileResolver],
|
||||
imports: [PrismaModule],
|
||||
providers: [ProfileService, ProfileResolver, SkillResolver],
|
||||
exports: [ProfileService],
|
||||
})
|
||||
export class ProfileModule {}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { Resolver, Query } from '@nestjs/graphql';
|
||||
import { ProfileDto } from './dto/index.js';
|
||||
|
||||
@Resolver()
|
||||
export class ProfileResolver {
|
||||
@Query(() => ProfileDto)
|
||||
async profile(): Promise<ProfileDto> {
|
||||
return {
|
||||
firstName: 'Евгений',
|
||||
lastName: 'Лубяной',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,91 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import { PrismaService } from '../prisma/prisma.service.js';
|
||||
import { ExperienceDto, LinkDto, ProfileDto, ProjectDto, SkillDto } from './dto/index.js';
|
||||
|
||||
@Injectable()
|
||||
export class ProfileService {}
|
||||
export class ProfileService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getProfile(): Promise<ProfileDto | null> {
|
||||
const profile = await this.prisma.profile.findFirst({ orderBy: { id: 'asc' } });
|
||||
if (!profile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: profile.id,
|
||||
firstName: profile.firstName,
|
||||
lastName: profile.lastName,
|
||||
description: profile.description,
|
||||
};
|
||||
}
|
||||
|
||||
async getProfiles(ids: number[]): Promise<ProfileDto[]> {
|
||||
const profiles = await this.prisma.profile.findMany({
|
||||
where: { id: { in: ids } },
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
|
||||
return profiles.map((profile) => ({
|
||||
id: profile.id,
|
||||
firstName: profile.firstName,
|
||||
lastName: profile.lastName,
|
||||
description: profile.description,
|
||||
}));
|
||||
}
|
||||
|
||||
async getSkills(profileIds: number[]): Promise<SkillDto[]> {
|
||||
const skills = await this.prisma.skill.findMany({
|
||||
where: { profileId: { in: profileIds } },
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
|
||||
return skills.map((skill) => ({
|
||||
profileId: skill.profileId,
|
||||
name: skill.name,
|
||||
}));
|
||||
}
|
||||
|
||||
async getLinks(profileIds: number[]): Promise<LinkDto[]> {
|
||||
const links = await this.prisma.link.findMany({
|
||||
where: { profileId: { in: profileIds } },
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
|
||||
return links.map((link) => ({
|
||||
profileId: link.profileId,
|
||||
name: link.name,
|
||||
link: link.link,
|
||||
}));
|
||||
}
|
||||
|
||||
async getExperiences(profileIds: number[]): Promise<ExperienceDto[]> {
|
||||
const experiences = await this.prisma.experience.findMany({
|
||||
where: { profileId: { in: profileIds } },
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
|
||||
return experiences.map((experience) => ({
|
||||
profileId: experience.profileId,
|
||||
company: experience.company,
|
||||
position: experience.position,
|
||||
period: experience.period,
|
||||
achievements: experience.achievements,
|
||||
}));
|
||||
}
|
||||
|
||||
async getProjects(profileIds: number[]): Promise<ProjectDto[]> {
|
||||
const projects = await this.prisma.project.findMany({
|
||||
where: { profileId: { in: profileIds } },
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
|
||||
return projects.map((project) => ({
|
||||
profileId: project.profileId,
|
||||
name: project.name,
|
||||
link: project.link,
|
||||
description: project.description,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { ProfileResolver } from './profile.resolver.js';
|
||||
export { SkillResolver } from './skill.resolver.js';
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Context, Parent, Query, ResolveField, Resolver } from '@nestjs/graphql';
|
||||
|
||||
import { ExperienceDto, LinkDto, ProfileDto, ProjectDto, SkillDto } from '../dto/index.js';
|
||||
import type { GraphQLContext } from '../profile.loaders.js';
|
||||
import { ProfileService } from '../profile.service.js';
|
||||
|
||||
/**
|
||||
* Точка входа GraphQL. Бизнес-логики нет: запрос профиля делегируется сервису,
|
||||
* вложенные данные догружаются лоадерами из контекста запроса.
|
||||
*/
|
||||
@Resolver(() => ProfileDto)
|
||||
export class ProfileResolver {
|
||||
constructor(private readonly profileService: ProfileService) {}
|
||||
|
||||
@Query(() => ProfileDto, { nullable: true, description: 'Профиль владельца визитки' })
|
||||
profile(): Promise<ProfileDto | null> {
|
||||
return this.profileService.getProfile();
|
||||
}
|
||||
|
||||
@ResolveField(() => [SkillDto], { description: 'Навыки' })
|
||||
skills(@Parent() profile: ProfileDto, @Context() context: GraphQLContext): Promise<SkillDto[]> {
|
||||
return context.loaders.skills.load(profile.id);
|
||||
}
|
||||
|
||||
@ResolveField(() => [LinkDto], { description: 'Ссылки на профессиональные ресурсы' })
|
||||
links(@Parent() profile: ProfileDto, @Context() context: GraphQLContext): Promise<LinkDto[]> {
|
||||
return context.loaders.links.load(profile.id);
|
||||
}
|
||||
|
||||
@ResolveField(() => [ExperienceDto], { description: 'Опыт работы' })
|
||||
experience(
|
||||
@Parent() profile: ProfileDto,
|
||||
@Context() context: GraphQLContext,
|
||||
): Promise<ExperienceDto[]> {
|
||||
return context.loaders.experience.load(profile.id);
|
||||
}
|
||||
|
||||
@ResolveField(() => [ProjectDto], { description: 'Проекты' })
|
||||
projects(
|
||||
@Parent() profile: ProfileDto,
|
||||
@Context() context: GraphQLContext,
|
||||
): Promise<ProjectDto[]> {
|
||||
return context.loaders.projects.load(profile.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Context, Parent, ResolveField, Resolver } from '@nestjs/graphql';
|
||||
|
||||
import { ProfileDto, SkillDto } from '../dto/index.js';
|
||||
import type { GraphQLContext } from '../profile.loaders.js';
|
||||
|
||||
@Resolver(() => SkillDto)
|
||||
export class SkillResolver {
|
||||
@ResolveField(() => ProfileDto, {
|
||||
description: 'Профиль, к которому относится навык',
|
||||
})
|
||||
profile(
|
||||
@Parent() skill: SkillDto,
|
||||
@Context() context: GraphQLContext,
|
||||
): Promise<ProfileDto | null> {
|
||||
return context.loaders.profiles.load(skill.profileId);
|
||||
}
|
||||
}
|
||||
@@ -3132,6 +3132,13 @@ __metadata:
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"dataloader@npm:^2.2.3":
|
||||
version: 2.2.3
|
||||
resolution: "dataloader@npm:2.2.3"
|
||||
checksum: 10c0/9b9a056fbc863ca86da87d59e053e871e263b4966aa4d55e40d61a65e96815fae5530ca220629064ca5f8e3000c0c4ec93292e170c38ff393fb34256b4d7c1aa
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"debug@npm:^4.3.7, debug@npm:^4.4.0, debug@npm:^4.4.3":
|
||||
version: 4.4.3
|
||||
resolution: "debug@npm:4.4.3"
|
||||
@@ -4095,6 +4102,7 @@ __metadata:
|
||||
"@types/pg": "npm:^8"
|
||||
"@types/supertest": "npm:^7.0.0"
|
||||
"@vitest/coverage-v8": "npm:^4.1.2"
|
||||
dataloader: "npm:^2.2.3"
|
||||
dotenv: "npm:^18.0.10"
|
||||
graphql: "npm:^17.1.0"
|
||||
oxlint: "npm:^1.58.0"
|
||||
|
||||
Reference in new issue
Block a user