Skip to content

Commit 6931a2e

Browse files
committed
chore: fastify & redis conf separate
1 parent 208dda5 commit 6931a2e

File tree

6 files changed

+82
-84
lines changed

6 files changed

+82
-84
lines changed

src/auth/auth/auth.service.ts

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,24 +14,20 @@ export class AuthService {
1414
constructor(private prisma: PrismaService) {}
1515

1616
async signupLocal(dto: AuthDto, req: FastifyRequest): Promise<Users> {
17-
1817
const existingUser = await this.prisma.users.findUnique({
1918
where: { username: dto.username, email: dto.email },
2019
})
2120
if (existingUser) {
2221
throw new BadRequestException('User already exists')
2322
}
2423

25-
2624
const hash = await argon.hash(dto.password)
2725
dto.password = undefined
2826

29-
3027
const newUser = await this.prisma.users.create({
3128
data: { ...dto, hash: hash },
3229
})
3330

34-
3531
await this.saveSession(req, newUser)
3632

3733
return newUser
@@ -69,7 +65,6 @@ export class AuthService {
6965
return user
7066
}
7167

72-
7368
const hash = await argon.hash(dto.password)
7469
dto.password = undefined
7570
const newUser = await this.prisma.users.create({
@@ -89,7 +84,6 @@ export class AuthService {
8984
remember?: boolean,
9085
): Promise<boolean> {
9186
return new Promise((resolve, reject) => {
92-
9387
if (remember) {
9488
req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 30 // 30 дней
9589
} else {

src/auth/oauth/github/github.contoller.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ export class GithubController {
2424
@Res() res: FastifyReply,
2525
) {
2626
try {
27-
2827
await this.githubOAuthService.authenticate(code, req)
2928
return res.redirect('/auth/status', 302) // переадресация на статус
3029
} catch (error) {

src/auth/oauth/google/google.service.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
import { Injectable } from '@nestjs/common'
32
import { OAuthService } from '../oauth.service'
43
import { AuthService } from 'src/auth/auth/auth.service'

src/main.ts

Lines changed: 2 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,7 @@ import { NestFactory } from '@nestjs/core'
22
import { AppModule } from './app.module'
33
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'
44
import * as cliColor from 'cli-color'
5-
import IORedis from 'ioredis'
6-
import * as fastifyCookie from '@fastify/cookie'
7-
import * as fastifySession from '@fastify/session'
8-
import * as fastifyCors from '@fastify/cors'
5+
import { registerFastifyPlugins } from './session/fastify.config'
96
import {
107
FastifyAdapter,
118
NestFastifyApplication,
@@ -20,78 +17,7 @@ async function bootstrap() {
2017
new FastifyAdapter(),
2118
)
2219

23-
await app.register(fastifyCors, {
24-
origin: ['http://127.0.0.1:9000', 'http://localhost:9000'],
25-
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
26-
credentials: true,
27-
})
28-
29-
await app.register(fastifyCookie)
30-
31-
const redis = new IORedis('redis://localhost:6379', {
32-
lazyConnect: true,
33-
connectTimeout: 5000,
34-
maxRetriesPerRequest: 3,
35-
})
36-
37-
await redis.ping()
38-
39-
redis.on('error', (err) => {
40-
console.error('Ошибка Redis:', err)
41-
})
42-
43-
redis.on('connect', () => {
44-
console.log('Подключение к Redis успешно!')
45-
})
46-
47-
redis.on('pong', (message) => {
48-
console.log('Redis ответил на ping:', message)
49-
})
50-
51-
redis.on('monitor', (time, args) => {
52-
console.log('Redis команда:', time, args)
53-
})
54-
55-
const customRedisStore = {
56-
get(sid: string, callback: (err?: any, session?: any) => void) {
57-
redis.get(`session:${sid}`, (err, data) => {
58-
if (err) return callback(err)
59-
if (!data) return callback()
60-
try {
61-
const session = JSON.parse(data)
62-
callback(null, session)
63-
} catch (error) {
64-
callback(error)
65-
}
66-
})
67-
},
68-
set(sid: string, session: any, callback: (err?: any) => void) {
69-
const ttl =
70-
session.cookie && session.cookie.maxAge
71-
? Math.floor(session.cookie.maxAge / 1000)
72-
: 24 * 60 * 60
73-
redis.set(`session:${sid}`, JSON.stringify(session), 'EX', ttl, (err) => {
74-
callback(err)
75-
})
76-
},
77-
destroy(sid: string, callback: (err?: any) => void) {
78-
redis.del(`session:${sid}`, (err) => {
79-
callback(err)
80-
})
81-
},
82-
}
83-
84-
await app.register(fastifySession, {
85-
secret: process.env.SESSION_SECRET || 'supersecret',
86-
saveUninitialized: false,
87-
cookie: {
88-
sameSite: 'lax',
89-
httpOnly: true,
90-
secure: false,
91-
maxAge: 24 * 60 * 60 * 1000,
92-
},
93-
store: customRedisStore,
94-
})
20+
registerFastifyPlugins(app)
9521

9622
const config = new DocumentBuilder()
9723
.setTitle('NestJS Fastify API')

src/session/fastify.config.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import * as fastifyCookie from '@fastify/cookie'
2+
import * as fastifySession from '@fastify/session'
3+
import * as fastifyCors from '@fastify/cors'
4+
import { customRedisStore } from './redis.provider'
5+
6+
export function registerFastifyPlugins(app) {
7+
app.register(fastifyCors, {
8+
origin: ['http://127.0.0.1:9000', 'http://localhost:9000'],
9+
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
10+
credentials: true,
11+
})
12+
13+
app.register(fastifyCookie)
14+
15+
app.register(fastifySession, {
16+
secret: process.env.SESSION_SECRET || 'supersecret',
17+
saveUninitialized: false,
18+
cookie: {
19+
sameSite: 'lax',
20+
httpOnly: true,
21+
secure: false,
22+
maxAge: 24 * 60 * 60 * 1000,
23+
},
24+
store: customRedisStore,
25+
})
26+
}

src/session/redis.provider.ts

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import IORedis from 'ioredis'
2+
3+
const redisUri = process.env.REDIS_URI || 'redis://localhost:6379'
4+
5+
export const redis = new IORedis(redisUri, {
6+
lazyConnect: true,
7+
connectTimeout: 5000,
8+
maxRetriesPerRequest: 3,
9+
})
10+
11+
redis.on('error', (err) => {
12+
console.error('Ошибка Redis:', err)
13+
})
14+
15+
redis.on('connect', () => {
16+
console.log('Подключение к Redis успешно!')
17+
})
18+
19+
redis.on('pong', (message) => {
20+
console.log('Redis ответил на ping:', message)
21+
})
22+
23+
redis.on('monitor', (time, args) => {
24+
console.log('Redis команда:', time, args)
25+
})
26+
27+
export const customRedisStore = {
28+
get(sid: string, callback: (err?: any, session?: any) => void) {
29+
redis.get(`session:${sid}`, (err, data) => {
30+
if (err) return callback(err)
31+
if (!data) return callback()
32+
try {
33+
const session = JSON.parse(data)
34+
callback(null, session)
35+
} catch (error) {
36+
callback(error)
37+
}
38+
})
39+
},
40+
set(sid: string, session: any, callback: (err?: any) => void) {
41+
const ttl =
42+
session.cookie && session.cookie.maxAge
43+
? Math.floor(session.cookie.maxAge / 1000)
44+
: 24 * 60 * 60
45+
redis.set(`session:${sid}`, JSON.stringify(session), 'EX', ttl, (err) => {
46+
callback(err)
47+
})
48+
},
49+
destroy(sid: string, callback: (err?: any) => void) {
50+
redis.del(`session:${sid}`, (err) => {
51+
callback(err)
52+
})
53+
},
54+
}

0 commit comments

Comments
 (0)