Application - Server - Supscription & Upload file
8/8/25About 1 min
Supscription:
Tạo kết nối realtime giữa client và server. Đầu tiên cần Enable giá trị installSubscriptionHandlers: true
trong GraphQlService và subscriptions
để verify token.
VD tạo subscription gửi thông báo cho client.
- GraqhQL Schema:
type NotifySubscription {
userId: String
message: String
createdAt: String
}
type Subscription {
notify: NotifySubscription! @isAuthenticated
}
Resolver:
import { PubSub } from 'graphql-subscriptions'; const pubSub = new PubSub(); ... @Subscription('notify') notify() { return pubSub.asyncIterator('notify'); }
Dùng class
PubSub
để kết nối App code (Nesjs) và GraphQL subscriptions engine. Subscribe qua methodasyncIterator
với tham số trigger name "notify".Publish:
Publish data bằng method
publish
const notify = { userId: user._id, message: "Welcome to app!", createdAt: new Date() }; pubSub.publish('notify', {notify});
Upload file:
Scalars: Mặc định GraphQL có các type:
Int
,Float
,String
,Boolean
andID
. Tạo thêm typeUpload
cho mutation upload file.@Scalar('Upload') export class Upload { description = 'Upload custom scalar type'; parseValue(value) { return GraphQLUpload.parseValue(value); } serialize(value: any) { return GraphQLUpload.serialize(value); } parseLiteral(valueNode, variables) { return GraphQLUpload.parseLiteral(valueNode, variables); } }
Khai báo provider tại module:
providers: [ Upload, ],
GraqhQL Schema:
type Mutation { profileAvatarUpdate(file: Upload!): Boolean @isAuthenticated }
Resolver:
import { GraphQLUpload, FileUpload } from 'graphql-upload'; import { createWriteStream } from 'fs'; @Mutation(() => Boolean) async profileAvatarUpdate( @Context('currentUser') currentUser: User, @Args({name: 'file', type: () => GraphQLUpload}) fileUpload: FileUpload, ): Promise<boolean> { const {createReadStream, filename} = fileInput; return new Promise(async (resolve, reject) => createReadStream() .pipe(createWriteStream(`/upload/${filename})`) .on('finish', () => resolve(true)) .on('error', (err) => { logger.error(err.toString()); reject(false); }), ); }
Series:
- Preview
- Server - NestJs & GraphQL
- Server - Module
- Server - Validation
- Server - Authentication
- Server - Supscription & Upload file
- Client - Angular & GraphQL
GitHub: https://github.com/ninhnguyen22/nestjs-angular-graphql