@@ -2,10 +2,7 @@ import { NestFactory } from '@nestjs/core'
22import { AppModule } from './app.module'
33import { SwaggerModule , DocumentBuilder } from '@nestjs/swagger'
44import * 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'
96import {
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' )
0 commit comments