Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Profiles #16

Merged
merged 5 commits into from
Feb 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"GitHub.copilot",
"GitHub.copilot-chat",
"esbenp.prettier-vscode",
"Orta.vscode-jest"
"Orta.vscode-jest",
"github.vscode-github-actions"
]
}
},
Expand Down
1 change: 1 addition & 0 deletions .devcontainer/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ services:
restart: unless-stopped
volumes:
- postgres-data:/var/lib/postgresql/data
- ./docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
environment:
POSTGRES_PASSWORD: postgres
POSTGRES_USER: postgres
Expand Down
3 changes: 3 additions & 0 deletions .devcontainer/docker-entrypoint-initdb.d/init.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
CREATE USER test WITH PASSWORD 'test';
CREATE DATABASE test;
GRANT ALL PRIVILEGES ON DATABASE test TO test;
11 changes: 5 additions & 6 deletions .env.test
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ JWT_ACCESS_TOKEN_EXPIRES_IN=10s
JWT_REFRESH_SECRET_TOKEN=fzeDYxqAwapb3GPWPn2hsPBKrDHDyQsKuGcLdikFhznnY6efbxpYSyWD6BxqTkSVpQTDH5XgD4q4qahUxDNaiFZsV4j2Vyy9HmPFNMBDJURxv5rvTTaw2zcTvQWtenz4
JWT_REFRESH_TOKEN_EXPIRES_IN=20s
GRAPHQL_COMPLEXITY_LIMIT=20
POSTGRES_USERNAME=waisy
POSTGRES_PASSWORD=1234
POSTGRES_DATABASE=waisy
POSTGRES_USERNAME=postgres
POSTGRES_PASSWORD=postgres
POSTGRES_DATABASE=test
POSTGRES_HOST=localhost
POSTGRES_PORT=5443
POSTGRES_SYNCHRONIZE=false
POSTGRES_MIGRATIONS_RUN=true
POSTGRES_SYNCHRONIZE=true
POSTGRES_MIGRATIONS_RUN=false
EMAIL_VERIFICATION_CODE_LIFETIME_MINUTES=10
EMAIL_VERIFICATION_CODE_MAX_SENDING_ATTEMPTS=3
EMAIL_VERIFICATION_CODE_MAX_INPUT_ATTEMPTS=3
Expand Down
7 changes: 4 additions & 3 deletions .github/workflows/node.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ jobs:
postgres:
image: postgres:${{ matrix.postgres-version }}
ports:
- 5443:5432
- 5432:5432
env:
POSTGRES_PASSWORD: 1234
POSTGRES_USER: waisy
POSTGRES_PASSWORD: postgres
POSTGRES_USER: postgres
POSTGRES_DB: test
options: >-
--health-cmd pg_isready
--health-interval 10s
Expand Down
3 changes: 2 additions & 1 deletion .vscode/extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"github.copilot-chat",
"esbenp.prettier-vscode",
"orta.vscode-jest",
"ms-vscode-remote.remote-containers"
"ms-vscode-remote.remote-containers",
"github.vscode-github-actions"
]
}
77 changes: 6 additions & 71 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,3 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" 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://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></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"/></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"></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

[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
Expand Down Expand Up @@ -58,39 +34,21 @@ $ npm run test:e2e
$ npm run test:cov
```

## 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://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)

## License

Nest is [MIT licensed](LICENSE).

# Notes
- Turn off VPN while the e2e tests are running

# Requirements

- Postgres 16.1
- Node.js 20.10.0

# Docker compose postgres
`docker compose -f docker-compose.local-postgres.yml up -d`

# Generate new migration
1. clear the postgres database of the application
2. `npm run migration:generate`
2. `npm run migration:run`
3. `npm run migration:generate`

# Create new migration
1. clear the postgres database of the application
2. `npm run migration:create`
3. write code to the created migration file
2. `npm run migration:run`
3. `npm run migration:create`
4. write code to the created migration file

# Run migration
1. `npm run migration:run`
Expand All @@ -108,33 +66,10 @@ Nest is [MIT licensed](LICENSE).
2. Put all env validation schemas to `src/config/env-validatiob-schemas.ts`
3. Put all resolvers to `src/schema-generator.script.ts`
4. Create/generate migrations if it needs
5. If you updated nodejs, change nodejs version in `Dockerfile`, `package.json` and `.github/workflows/node.yml`
5. If you updated nodejs, change nodejs version in `Dockerfile`, `package.json`, `.github/workflows/node.yml` and `.devcontainer`
6. If you updated postgres, change `.github/workflows/node.yml`
7. `npm run format:check`
8. `npm run link:check`
9. `npm run test`
10. `npm run test:e2e`
11. Push commit

# Requirements

- Postgres 16.1
- Node.js 20.10.0

# Docker compose postgres
`docker compose -f docker-compose.local-postgres.yml up -d`

# Generate new migration
1. clear the postgres database of the application
2. `npm run migration:generate`

# Create new migration
1. clear the postgres database of the application
2. `npm run migration:create`
3. write code to the created migration file

# Run migration
1. `npm run migration:run`

# Revert migration
1. `npm run migration:revert`
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
"testEnvironment": "node",
"moduleNameMapper": {
"^src/(.*)$": "<rootDir>/$1"
}
}
}
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {ValidationModule} from './validation/validation.module'
import {GraphqlModule} from './graphql/graphql.module'
import {CryptModule} from './crypt/crypt.module'
import {TypeOrmModule} from './type-orm/type-orm.module'
import {ProfileModule} from './profile/profile.module'
// TODO: переписать тесты под нативный test_runner
@Module({
imports: [
Expand All @@ -26,6 +27,7 @@ import {TypeOrmModule} from './type-orm/type-orm.module'
GraphqlModule,
CryptModule,
TypeOrmModule,
ProfileModule,
],
})
export class AppModule {}
2 changes: 2 additions & 0 deletions src/email-verification/email-verification.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ export class EmailVerificationService {
const user = await this.usersService.getOrCreateUserByEmail(email)
const verificationCode = await this.getOrCreateVerificationCodeByUser(user)

this.logger.debug(`Sending verification code "${verificationCode.code}" to email "${email}"`)

await this.unisenderService.sendEmailVerification(email, verificationCode.code)
}

Expand Down
31 changes: 31 additions & 0 deletions src/migrations/1708534487221-migration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {MigrationInterface, QueryRunner} from 'typeorm'

export class Migration1708534487221 implements MigrationInterface {
name = 'Migration1708534487221'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE TABLE "profile" (
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"title" character varying NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"ownerId" uuid NOT NULL,
CONSTRAINT "PK_3dd8bfc97e4a77c70971591bdcb" PRIMARY KEY ("id")
)
`)
await queryRunner.query(`
ALTER TABLE "profile"
ADD CONSTRAINT "FK_552aa6698bb78970f6569161ec0" FOREIGN KEY ("ownerId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION
`)
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE "profile" DROP CONSTRAINT "FK_552aa6698bb78970f6569161ec0"
`)
await queryRunner.query(`
DROP TABLE "profile"
`)
}
}
11 changes: 11 additions & 0 deletions src/profile/dto/create-profile.args.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {ArgsType, Field} from '@nestjs/graphql'
import {IsNotEmpty, IsString, MaxLength} from 'class-validator'

@ArgsType()
export class CreateProfileArgs {
@Field({description: 'The title of the profile', nullable: false})
@IsString({message: 'must be a string'})
@IsNotEmpty({message: 'must not be empty'})
@MaxLength(100, {message: 'must be shorter than or equal to 100 characters'})
title: string
}
29 changes: 29 additions & 0 deletions src/profile/entities/profile.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import {User} from '../../users/entities/user.entity'
import {
Column,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm'

@Entity()
export class Profile {
@PrimaryGeneratedColumn('uuid')
id: string

@Column()
title: string

@ManyToOne(() => User, {onDelete: 'CASCADE', nullable: false, eager: true})
@JoinColumn()
owner: User

@CreateDateColumn({type: 'timestamp with time zone'})
createdAt: Date

@UpdateDateColumn({type: 'timestamp with time zone'})
updatedAt: Date
}
10 changes: 10 additions & 0 deletions src/profile/models/profile.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {Field, ObjectType} from '@nestjs/graphql'

@ObjectType({description: 'The profile model'})
export class Profile {
@Field({description: 'The ID of the profile'})
id: string

@Field({description: 'The title of the profile'})
title: string
}
11 changes: 11 additions & 0 deletions src/profile/profile.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {Module} from '@nestjs/common'
import {ProfileService} from './profile.service'
import {ProfileResolver} from './profile.resolver'
import {Profile} from './entities/profile.entity'
import {TypeOrmModule} from '@nestjs/typeorm'

@Module({
imports: [TypeOrmModule.forFeature([Profile])],
providers: [ProfileService, ProfileResolver],
})
export class ProfileModule {}
41 changes: 41 additions & 0 deletions src/profile/profile.resolver.descriptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import {UnauthorizedError} from '../errors/general-errors/unauthorized.error'
import {InternalServerError} from '../errors/general-errors/internal-server.error'
import {ValidationError} from '../errors/general-errors/validation.error'
import {RequestTimeoutError} from '../errors/general-errors/request-timeout.error'
import {ComplexityLimitError} from '../errors/general-errors/complexity-limit.error'
import {ForbiddenError} from '../errors/general-errors/forbidden.error'

export const resolverDescriptions = {
createProfile: `
Create a new profile for the current user.

**Error codes:**

- \`${ForbiddenError.code}\` - You have reached the limit of profiles.

- \`${UnauthorizedError.code}\` - Access token is invalid or expired.

- \`${InternalServerError.code}\`

- \`${ValidationError.code}\`

- \`${RequestTimeoutError.code}\`

- \`${ComplexityLimitError.code}\`
`,
getProfiles: `
Get all profiles for the current user.

**Error codes:**

- \`${UnauthorizedError.code}\` - Access token is invalid or expired.

- \`${InternalServerError.code}\`

- \`${ValidationError.code}\`

- \`${RequestTimeoutError.code}\`

- \`${ComplexityLimitError.code}\`
`,
}
Loading