Skip to content

Commit

Permalink
refactor: Update file permission function to validate request body
Browse files Browse the repository at this point in the history
  • Loading branch information
xuelink committed Jun 26, 2024
1 parent ef0bca5 commit 1ebd411
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
14 changes: 13 additions & 1 deletion functions/update-file-permission/src/main.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Client, Databases, Query } from 'node-appwrite';
import { Client, Databases } from 'node-appwrite';

import { throwIfMissing } from './utils.js';

// Event Triggers
// "events": [
Expand All @@ -17,6 +19,16 @@ export default async ({ req, res, log, error }) => {

log('update-file-permission');

try {
log(req.body);
const requestBody = JSON.parse(req.body);
throwIfMissing(requestBody, ['to', 'fileId', 'type']);

return res.json({ ok: true });
} catch (err) {
return res.json({ ok: false, error: err.message }, 400);
}

try {
log(req.body);
return res.json({ ok: true });
Expand Down
17 changes: 17 additions & 0 deletions functions/update-file-permission/src/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Throws an error if any of the keys are missing from the object
* @param {*} obj
* @param {string[]} keys
* @throws {Error}
*/
export function throwIfMissing(obj, keys) {
const missing = [];
for (let key of keys) {
if (!(key in obj) || !obj[key]) {
missing.push(key);
}
}
if (missing.length > 0) {
throw new Error(`Missing required fields: ${missing.join(', ')}`);
}
}

0 comments on commit 1ebd411

Please sign in to comment.