diff --git a/server/commands/documentLoader.ts b/server/commands/documentLoader.ts index 24132ce9a0..4b717f0a40 100644 --- a/server/commands/documentLoader.ts +++ b/server/commands/documentLoader.ts @@ -1,4 +1,3 @@ -import invariant from "invariant"; import { Op, WhereOptions } from "sequelize"; import isUUID from "validator/lib/isUUID"; import { UrlHelper } from "@shared/utils/UrlHelper"; @@ -22,8 +21,8 @@ type Props = { type Result = { document: Document; - share?: Share; - collection?: Collection | null; + share: Share | null; + collection: Collection | null; }; export default async function loadDocument({ @@ -33,9 +32,9 @@ export default async function loadDocument({ user, includeState, }: Props): Promise { - let document; - let collection; - let share; + let document: Document | null = null; + let collection: Collection | null = null; + let share: Share | null = null; if (!shareId && !(id && user)) { throw AuthenticationError(`Authentication or shareId required`); @@ -72,20 +71,7 @@ export default async function loadDocument({ where: whereClause, include: [ { - // unscoping here allows us to return unpublished documents - model: Document.unscoped(), - include: [ - { - model: User, - as: "createdBy", - paranoid: false, - }, - { - model: User, - as: "updatedBy", - paranoid: false, - }, - ], + model: Document.scope("withDrafts"), required: true, as: "document", }, @@ -129,14 +115,13 @@ export default async function loadDocument({ const canReadDocument = user && can(user, "read", document); if (canReadDocument) { - // Cannot use document.collection here as it does not include the - // documentStructure by default through the relationship. if (document.collectionId) { - collection = await Collection.findByPk(document.collectionId); - - if (!collection) { - throw NotFoundError("Collection could not be found for document"); - } + collection = await Collection.scope("withDocumentStructure").findByPk( + document.collectionId, + { + rejectOnEmpty: true, + } + ); } return { @@ -155,11 +140,15 @@ export default async function loadDocument({ // It is possible to disable sharing at the collection so we must check if (document.collectionId) { - collection = await Collection.findByPk(document.collectionId); + collection = await Collection.scope("withDocumentStructure").findByPk( + document.collectionId, + { + rejectOnEmpty: true, + } + ); } - invariant(collection, "collection not found"); - if (!collection.sharing) { + if (!collection?.sharing) { throw AuthorizationError(); } diff --git a/server/commands/documentMover.ts b/server/commands/documentMover.ts index cf1b150783..e8629b94ad 100644 --- a/server/commands/documentMover.ts +++ b/server/commands/documentMover.ts @@ -1,4 +1,3 @@ -import invariant from "invariant"; import { Transaction } from "sequelize"; import { createContext } from "@server/context"; import { traceFunction } from "@server/logging/tracing"; @@ -66,16 +65,21 @@ async function documentMover({ result.documents.push(document); } else { // Load the current and the next collection upfront and lock them - const collection = await Collection.findByPk(document.collectionId!, { - transaction, - lock: Transaction.LOCK.UPDATE, - paranoid: false, - }); + const collection = await Collection.scope("withDocumentStructure").findByPk( + document.collectionId!, + { + transaction, + lock: Transaction.LOCK.UPDATE, + paranoid: false, + } + ); let newCollection = collection; if (collectionChanged) { if (collectionId) { - newCollection = await Collection.findByPk(collectionId, { + newCollection = await Collection.scope( + "withDocumentStructure" + ).findByPk(collectionId, { transaction, lock: Transaction.LOCK.UPDATE, }); @@ -144,12 +148,15 @@ async function documentMover({ if (collectionId) { // Reload the collection to get relationship data - newCollection = await Collection.scope({ - method: ["withMembership", user.id], - }).findByPk(collectionId, { + newCollection = await Collection.scope([ + "withDocumentStructure", + { + method: ["withMembership", user.id], + }, + ]).findByPk(collectionId, { transaction, + rejectOnEmpty: true, }); - invariant(newCollection, "Collection not found"); result.collections.push(newCollection); diff --git a/server/models/Collection.test.ts b/server/models/Collection.test.ts index 46a076b1b2..d91d4c1323 100644 --- a/server/models/Collection.test.ts +++ b/server/models/Collection.test.ts @@ -297,7 +297,7 @@ describe("#updateDocument", () => { newDocument.title = "Updated title"; await newDocument.save(); await collection.updateDocument(newDocument); - const reloaded = await Collection.findByPk(collection.id); + const reloaded = await collection.reload(); expect(reloaded!.documentStructure![0].children[0].title).toBe( "Updated title" ); @@ -380,7 +380,7 @@ describe("#removeDocument", () => { expect(collection.documentStructure![0].children.length).toBe(1); // Remove the document await collection.deleteDocument(newDocument); - const reloaded = await Collection.findByPk(collection.id); + const reloaded = await collection.reload(); expect(reloaded!.documentStructure!.length).toBe(1); expect(reloaded!.documentStructure![0].children.length).toBe(0); const collectionDocuments = await Document.findAndCountAll({ diff --git a/server/models/Collection.ts b/server/models/Collection.ts index 3c15ffcacd..47fb4d8c3d 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -37,6 +37,7 @@ import { AllowNull, BeforeCreate, BeforeUpdate, + DefaultScope, } from "sequelize-typescript"; import isUUID from "validator/lib/isUUID"; import type { CollectionSort, ProsemirrorData } from "@shared/types"; @@ -69,6 +70,11 @@ type AdditionalFindOptions = { rejectOnEmpty?: boolean | Error; }; +@DefaultScope(() => ({ + attributes: { + exclude: ["documentStructure"], + }, +})) @Scopes(() => ({ withAllMemberships: { include: [ @@ -121,6 +127,12 @@ type AdditionalFindOptions = { }, ], }), + withDocumentStructure: () => ({ + attributes: { + // resets to include the documentStructure column + exclude: [], + }, + }), withMembership: (userId: string) => { if (!userId) { return {}; diff --git a/server/models/Document.ts b/server/models/Document.ts index 851f25089e..612524cdf9 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -414,10 +414,13 @@ class Document extends ArchivableModel< return; } - const collection = await Collection.findByPk(model.collectionId, { - transaction, - lock: Transaction.LOCK.UPDATE, - }); + const collection = await Collection.scope("withDocumentStructure").findByPk( + model.collectionId, + { + transaction, + lock: Transaction.LOCK.UPDATE, + } + ); if (!collection) { return; } @@ -438,7 +441,9 @@ class Document extends ArchivableModel< } return this.sequelize!.transaction(async (transaction: Transaction) => { - const collection = await Collection.findByPk(model.collectionId!, { + const collection = await Collection.scope( + "withDocumentStructure" + ).findByPk(model.collectionId!, { transaction, lock: transaction.LOCK.UPDATE, }); @@ -926,7 +931,9 @@ class Document extends ArchivableModel< } if (!this.template && this.collectionId) { - const collection = await Collection.findByPk(this.collectionId, { + const collection = await Collection.scope( + "withDocumentStructure" + ).findByPk(this.collectionId, { transaction, lock: Transaction.LOCK.UPDATE, }); @@ -993,10 +1000,13 @@ class Document extends ArchivableModel< await this.sequelize.transaction(async (transaction: Transaction) => { const collection = this.collectionId - ? await Collection.findByPk(this.collectionId, { - transaction, - lock: transaction.LOCK.UPDATE, - }) + ? await Collection.scope("withDocumentStructure").findByPk( + this.collectionId, + { + transaction, + lock: transaction.LOCK.UPDATE, + } + ) : undefined; if (collection) { @@ -1027,10 +1037,13 @@ class Document extends ArchivableModel< archive = async (user: User, options?: FindOptions) => { const { transaction } = { ...options }; const collection = this.collectionId - ? await Collection.findByPk(this.collectionId, { - transaction, - lock: transaction?.LOCK.UPDATE, - }) + ? await Collection.scope("withDocumentStructure").findByPk( + this.collectionId, + { + transaction, + lock: transaction?.LOCK.UPDATE, + } + ) : undefined; if (collection) { @@ -1051,7 +1064,7 @@ class Document extends ArchivableModel< ) => { const { transaction } = { ...options }; const collection = collectionId - ? await Collection.findByPk(collectionId, { + ? await Collection.scope("withDocumentStructure").findByPk(collectionId, { transaction, lock: transaction?.LOCK.UPDATE, }) @@ -1103,7 +1116,9 @@ class Document extends ArchivableModel< let deleted = false; if (!this.template && this.collectionId) { - const collection = await Collection.findByPk(this.collectionId!, { + const collection = await Collection.scope( + "withDocumentStructure" + ).findByPk(this.collectionId!, { transaction, lock: transaction.LOCK.UPDATE, paranoid: false, diff --git a/server/routes/api/collections/collections.ts b/server/routes/api/collections/collections.ts index 8dccd775da..f61f47e17e 100644 --- a/server/routes/api/collections/collections.ts +++ b/server/routes/api/collections/collections.ts @@ -140,9 +140,12 @@ router.post( async (ctx: APIContext) => { const { id } = ctx.input.body; const { user } = ctx.state.auth; - const collection = await Collection.scope({ - method: ["withMembership", user.id], - }).findByPk(id); + const collection = await Collection.scope([ + "withDocumentStructure", + { + method: ["withMembership", user.id], + }, + ]).findByPk(id); authorize(user, "readDocument", collection); diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 986f366ce2..677d7db99e 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -977,7 +977,7 @@ describe("#documents.list", () => { const res = await server.post("/api/documents.list", { body: { token: user.getJwtToken(), - collection: document.collectionId, + collectionId: document.collectionId, }, }); const body = await res.json(); @@ -1013,7 +1013,7 @@ describe("#documents.list", () => { const res = await server.post("/api/documents.list", { body: { token: user.getJwtToken(), - collection: collection.id, + collectionId: collection.id, }, }); const body = await res.json(); diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 8e626ed7a5..5c985e3ec0 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -133,15 +133,19 @@ router.post( // if a specific collection is passed then we need to check auth to view it if (collectionId) { where[Op.and].push({ collectionId: [collectionId] }); - const collection = await Collection.scope({ - method: ["withMembership", user.id], - }).findByPk(collectionId); + const collection = await Collection.scope([ + ...(sort === "index" ? ["withDocumentStructure"] : []), + { + method: ["withMembership", user.id], + }, + ]).findByPk(collectionId); + authorize(user, "readDocument", collection); // index sort is special because it uses the order of the documents in the // collection.documentStructure rather than a database column if (sort === "index") { - documentIds = (collection?.documentStructure || []) + documentIds = (collection.documentStructure || []) .map((node) => node.id) .slice(ctx.state.pagination.offset, ctx.state.pagination.limit); where[Op.and].push({ id: documentIds }); diff --git a/server/test/factories.ts b/server/test/factories.ts index f215227bec..caadbd9aef 100644 --- a/server/test/factories.ts +++ b/server/test/factories.ts @@ -310,7 +310,7 @@ export async function buildCollection( overrides.permission = CollectionPermission.ReadWrite; } - return Collection.create({ + return Collection.scope("withDocumentStructure").create({ name: faker.lorem.words(2), description: faker.lorem.words(4), createdById: overrides.userId,