-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathworkspace-documents.service.ts
202 lines (176 loc) · 4.74 KB
/
workspace-documents.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import { Injectable, NotFoundException } from "@nestjs/common";
import { Document, Prisma } from "@prisma/client";
import { PrismaService } from "src/db/prisma.service";
import { FindWorkspaceDocumentsResponse } from "./types/find-workspace-documents-response.type";
import { CreateWorkspaceDocumentShareTokenResponse } from "./types/create-workspace-document-share-token-response.type";
import { ShareRole } from "src/utils/types/share-role.type";
import { generateRandomKey } from "src/utils/functions/random-string";
import { ConfigService } from "@nestjs/config";
import { FindDocumentsFromYorkieResponse } from "./types/find-documents-from-yorkie-response.type";
import * as moment from "moment";
import { connect } from "http2";
@Injectable()
export class WorkspaceDocumentsService {
constructor(
private prismaService: PrismaService,
private configService: ConfigService
) {}
async create(userId: string, workspaceId: string, title: string) {
try {
await this.prismaService.userWorkspace.findFirstOrThrow({
where: {
userId,
workspaceId,
},
});
} catch (e) {
throw new NotFoundException();
}
return this.prismaService.document.create({
data: {
title,
workspaceId,
yorkieDocumentId: Math.random().toString(36).substring(7),
},
});
}
async findMany(
userId: string,
workspaceId: string,
pageSize: number,
cursor?: string
): Promise<FindWorkspaceDocumentsResponse> {
try {
await this.prismaService.userWorkspace.findFirstOrThrow({
where: {
userId,
workspaceId,
},
});
} catch (e) {
throw new NotFoundException();
}
const additionalOptions: Prisma.DocumentFindManyArgs = {};
if (cursor) {
additionalOptions.cursor = { id: cursor };
}
const totalLength = await this.prismaService.document.count({
where: {
workspaceId,
},
});
const documentList = await this.prismaService.document.findMany({
take: pageSize + 1,
where: {
workspaceId,
},
orderBy: {
id: "desc",
},
...additionalOptions,
});
const slicedDocumentList = documentList.slice(0, pageSize);
const yorkieDocumentList = await this.findManyFromYorkie(
slicedDocumentList.map((doc) => doc.yorkieDocumentId)
);
const mergedDocumentList = slicedDocumentList.map((doc, idx) => {
const yorkieDocument = yorkieDocumentList.documents?.[idx];
return {
...doc,
updatedAt: yorkieDocument?.updatedAt
? moment(yorkieDocument.updatedAt).toDate()
: doc.updatedAt,
};
});
return {
documents: mergedDocumentList,
cursor: documentList.length > pageSize ? documentList[pageSize].id : null,
totalLength,
};
}
async findOne(userId: string, workspaceId: string, documentId: string) {
try {
await this.prismaService.userWorkspace.findFirstOrThrow({
where: {
userId,
workspaceId,
},
});
return this.prismaService.document.findUniqueOrThrow({
where: {
id: documentId,
},
});
} catch (e) {
throw new NotFoundException();
}
}
async createSharingToken(
userId: string,
workspaceId: string,
documentId: string,
role: ShareRole,
expirationDate: Date
): Promise<CreateWorkspaceDocumentShareTokenResponse> {
let document: Document;
try {
await this.prismaService.userWorkspace.findFirstOrThrow({
where: {
userId,
workspaceId,
},
});
document = await this.prismaService.document.findUniqueOrThrow({
where: {
id: documentId,
workspaceId,
},
});
} catch (e) {
throw new NotFoundException();
}
const token = generateRandomKey();
await this.prismaService.documentSharingToken.create({
data: {
documentId: document.id,
token,
expiredAt: expirationDate,
role,
},
});
return {
sharingToken: token,
};
}
async findManyFromYorkie(
documentKeyList: Array<string>
): Promise<FindDocumentsFromYorkieResponse | undefined> {
return new Promise((resolve, reject) => {
const client = connect(`${this.configService.get<string>("YORKIE_API_ADDR")}`);
client.on("error", (err) => reject(err));
const requestBody = JSON.stringify({
project_name: this.configService.get<string>("YORKIE_PROJECT_NAME"),
document_keys: documentKeyList,
include_snapshot: false,
});
const req = client.request({
":method": "POST",
":path": "/yorkie.v1.AdminService/GetDocuments",
"Content-Type": "application/json",
"content-length": Buffer.byteLength(requestBody),
Authorization: this.configService.get<string>("YORKIE_PROJECT_SECRET_KEY"),
});
req.write(requestBody);
req.setEncoding("utf8");
let data = "";
req.on("data", (chunk) => {
data += chunk;
});
req.on("end", () => {
client.close();
resolve(JSON.parse(data) as FindDocumentsFromYorkieResponse);
});
req.end();
});
}
}