Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ const mockModel = {
findOneAndUpdate: mockFindOneAndUpdate,
};

const mockDispatchWebhooks = jest.fn();
const mockWebhookQueueAdd = jest.fn();

jest.mock('@urbackend/common', () => ({
Project: {
findOne: mockFindOne,
},
getConnection: jest.fn().mockResolvedValue({}),
getCompiledModel: jest.fn(() => mockModel),
dispatchWebhooks: mockDispatchWebhooks,
webhookQueue: { add: mockWebhookQueueAdd },
enqueueCollectionCleanup: jest.fn().mockResolvedValue(true),
syncCollectionCleanup: jest.fn().mockResolvedValue(true),
AppError: class AppError extends Error {
Expand Down Expand Up @@ -161,11 +161,16 @@ describe('Soft Delete in dashboard project.controller', () => {
message: "Document recovered from trash"
});

expect(mockDispatchWebhooks).toHaveBeenCalledWith(expect.objectContaining({
action: 'recover',
document: restoredDoc,
projectId: 'proj_1'
}));
expect(mockWebhookQueueAdd).toHaveBeenCalledWith(
'trigger-webhook',
expect.objectContaining({
event: 'document.recovered',
payload: restoredDoc,
projectId: 'proj_1',
collection: 'posts'
}),
{ removeOnComplete: true }
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
const { syncCollectionCleanup } = require('@urbackend/common');
expect(syncCollectionCleanup).toHaveBeenCalledWith('proj_1', 'posts');
});
Expand Down
12 changes: 5 additions & 7 deletions apps/dashboard-api/src/controllers/project.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const { getConnection } = require("@urbackend/common");
const { getCompiledModel } = require("@urbackend/common");
const { QueryEngine } = require("@urbackend/common");
const { storageRegistry } = require("@urbackend/common");
const { AppError, dispatchWebhooks, enqueueCollectionCleanup, syncCollectionCleanup } = require("@urbackend/common");
const { AppError, webhookQueue, enqueueCollectionCleanup, syncCollectionCleanup } = require("@urbackend/common");
const { resolveEffectivePlan } = require("@urbackend/common");
const {
deleteProjectByApiKeyCache,
Expand Down Expand Up @@ -1055,14 +1055,12 @@ module.exports.recoverRow = async (req, res, next) => {
return next(new AppError(404, "Document not found or recovery window expired (30 days)."));
}

dispatchWebhooks({
await webhookQueue.add('trigger-webhook', {
projectId: project._id,
event: 'document.recovered',
collection: collectionName,
action: "recover",
document: result,
documentId: id,
options: { bypassLimit: true }
});
payload: result
}, { removeOnComplete: true });

try {
await syncCollectionCleanup(projectId, collectionName);
Expand Down
19 changes: 12 additions & 7 deletions apps/public-api/src/__tests__/softDelete.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jest.mock('@urbackend/common', () => {
Project: {},
getConnection: jest.fn().mockResolvedValue({}),
getCompiledModel: jest.fn(() => mockModel),
dispatchWebhooks: jest.fn(),
webhookQueue: { add: jest.fn() },
QueryEngine: jest.fn(),
validateData: jest.fn(),
validateUpdateData: jest.fn(),
Expand Down Expand Up @@ -138,12 +138,17 @@ describe('Soft Delete in data.controller', () => {
message: "Document recovered from trash"
});

const { dispatchWebhooks, syncCollectionCleanup } = require('@urbackend/common');
expect(dispatchWebhooks).toHaveBeenCalledWith(expect.objectContaining({
action: 'recover',
document: restoredDoc,
projectId: 'proj_1'
}));
const { webhookQueue, syncCollectionCleanup } = require('@urbackend/common');
expect(webhookQueue.add).toHaveBeenCalledWith(
'trigger-webhook',
expect.objectContaining({
event: 'document.recovered',
payload: restoredDoc,
projectId: 'proj_1',
collection: 'posts'
}),
{ removeOnComplete: true }
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
expect(syncCollectionCleanup).toHaveBeenCalledWith('proj_1', 'posts');
});

Expand Down
39 changes: 17 additions & 22 deletions apps/public-api/src/controllers/data.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { Project } = require("@urbackend/common");
const { getConnection } = require("@urbackend/common");
const { getCompiledModel } = require("@urbackend/common");
const { QueryEngine } = require("@urbackend/common");
const { validateData, validateUpdateData, aggregateSchema, dispatchWebhooks } = require("@urbackend/common");
const { validateData, validateUpdateData, aggregateSchema, webhookQueue } = require("@urbackend/common");
const { performance } = require('perf_hooks');
const { z } = require("zod");
const {
Expand Down Expand Up @@ -83,13 +83,12 @@ module.exports.insertData = async (req, res) => {
);
}

dispatchWebhooks({
await webhookQueue.add('trigger-webhook', {
projectId: project._id,
event: 'document.inserted',
collection: collectionName,
action: 'insert',
document: result.toObject ? result.toObject() : result,
documentId: result._id,
});
payload: result.toObject ? result.toObject() : result
}, { removeOnComplete: true });

if (isDebug) console.log(`[DEBUG] insert data took ${(performance.now() - start).toFixed(2)}ms`);
res.status(201).json(result);
Expand Down Expand Up @@ -536,13 +535,12 @@ module.exports.updateSingleData = async (req, res) => {

if (!result) return res.status(404).json({ error: "Document not found." });

dispatchWebhooks({
await webhookQueue.add('trigger-webhook', {
projectId: project._id,
event: 'document.updated',
collection: collectionName,
action: 'update',
document: result,
documentId: result._id,
});
payload: result
}, { removeOnComplete: true });

res.json({ message: "Updated", data: result });
} catch (err) {
Expand Down Expand Up @@ -610,13 +608,12 @@ module.exports.deleteSingleDoc = async (req, res) => {
console.error("Failed to enqueue trash cleanup job", { projectId: String(project._id), collectionName, err });
}

dispatchWebhooks({
await webhookQueue.add('trigger-webhook', {
projectId: project._id,
event: 'document.deleted',
collection: collectionName,
action: 'delete',
document: result,
documentId: id,
});
payload: result
}, { removeOnComplete: true });

res.json({ success: true, data: { id }, message: "Document moved to trash" });
} catch (err) {
Expand Down Expand Up @@ -679,14 +676,12 @@ module.exports.recoverSingleDoc = async (req, res, next) => {
return next(new AppError(404, "Document not found or recovery window expired (30 days)."));
}

dispatchWebhooks({
await webhookQueue.add('trigger-webhook', {
projectId: project._id,
event: 'document.recovered',
collection: collectionName,
action: 'recover',
document: result,
documentId: id,
options: {}
});
payload: result
}, { removeOnComplete: true });

try {
await syncCollectionCleanup(project._id, collectionName);
Expand Down
24 changes: 24 additions & 0 deletions packages/common/src/queues/webhookQueue.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,30 @@ function initWebhookWorker() {
const worker = new Worker(
"webhook-delivery-queue",
async (job) => {
if (job.name === "trigger-webhook") {
const { projectId, event, collection, payload } = job.data;
const { dispatchWebhooks } = require("../utils/webhookDispatcher");

let action = "update";
if (event.includes("inserted")) action = "insert";
if (event.includes("deleted")) action = "delete";
if (event.includes("recovered")) action = "recover";

try {
await dispatchWebhooks({
projectId,
collection,
action,
document: payload,
documentId: payload?._id,
});
} catch (error) {
console.error(`[Webhook] trigger-webhook failed for projectId: ${projectId}, collection: ${collection}, action: ${action}, documentId: ${payload?._id}`, error);
throw error;
}
return;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const { deliveryId, webhookId, attemptNumber } = job.data;

try {
Expand Down
Loading