feat(server): userDoc model (#9835)

close CLOUD-104
This commit is contained in:
fengmk2
2025-02-06 02:50:28 +00:00
parent b40f007ccf
commit 8e7cfb6115
3 changed files with 215 additions and 0 deletions

View File

@@ -13,6 +13,7 @@ import { PageModel } from './page';
import { MODELS_SYMBOL } from './provider';
import { SessionModel } from './session';
import { UserModel } from './user';
import { UserDocModel } from './user-doc';
import { UserFeatureModel } from './user-feature';
import { VerificationTokenModel } from './verification-token';
import { WorkspaceModel } from './workspace';
@@ -28,6 +29,7 @@ const MODELS = {
userFeature: UserFeatureModel,
workspaceFeature: WorkspaceFeatureModel,
doc: DocModel,
userDoc: UserDocModel,
};
type ModelsType = {
@@ -85,6 +87,7 @@ export * from './feature';
export * from './page';
export * from './session';
export * from './user';
export * from './user-doc';
export * from './user-feature';
export * from './verification-token';
export * from './workspace';

View File

@@ -0,0 +1,116 @@
import { Injectable } from '@nestjs/common';
import { BaseModel } from './base';
import { Doc } from './common';
/**
* User Doc Model
*/
@Injectable()
export class UserDocModel extends BaseModel {
async upsert(doc: Doc) {
const row = await this.db.userSnapshot.upsert({
where: {
userId_id: {
userId: doc.spaceId,
id: doc.docId,
},
},
update: {
blob: doc.blob,
updatedAt: new Date(doc.timestamp),
},
create: {
userId: doc.spaceId,
id: doc.docId,
blob: doc.blob,
createdAt: new Date(doc.timestamp),
updatedAt: new Date(doc.timestamp),
},
select: {
updatedAt: true,
},
});
return row;
}
async get(userId: string, docId: string): Promise<Doc | null> {
const row = await this.db.userSnapshot.findUnique({
where: {
userId_id: {
userId,
id: docId,
},
},
});
if (!row) {
return null;
}
return {
spaceId: row.userId,
docId: row.id,
blob: row.blob,
timestamp: row.updatedAt.getTime(),
editorId: row.userId,
};
}
/**
* Find the timestamps of user docs by userId.
*
* @param after Only return timestamps after this timestamp.
*/
async findTimestampsByUserId(userId: string, after?: number) {
const snapshots = await this.db.userSnapshot.findMany({
select: {
id: true,
updatedAt: true,
},
where: {
userId,
...(after
? {
updatedAt: {
gt: new Date(after),
},
}
: {}),
},
});
const result: Record<string, number> = {};
snapshots.forEach(s => {
result[s.id] = s.updatedAt.getTime();
});
return result;
}
/**
* Delete a user doc by userId and docId.
*/
async delete(userId: string, docId: string) {
await this.db.userSnapshot.deleteMany({
where: {
userId,
id: docId,
},
});
this.logger.log(`Deleted user ${userId} doc ${docId}`);
}
/**
* Delete all user docs by userId.
*/
async deleteAllByUserId(userId: string) {
const { count } = await this.db.userSnapshot.deleteMany({
where: {
userId,
},
});
this.logger.log(`Deleted user ${userId} ${count} docs`);
return count;
}
}