Skip to content

Instantly share code, notes, and snippets.

@IwateKyle
Created September 11, 2023 03:35
Show Gist options
  • Save IwateKyle/5e592a1e7e766789f983e4a04d84ed61 to your computer and use it in GitHub Desktop.
Save IwateKyle/5e592a1e7e766789f983e4a04d84ed61 to your computer and use it in GitHub Desktop.
PocketBase - updating a record's fields before the request is created or updated in the database.
onRecordBeforeCreateRequest((e) => {
const requestInfo = $apis.requestInfo(e.httpContext);
// Update createdBy and updatedBy fields
if (requestInfo.authRecord !== null) {
e.record.set(
'createdBy',
`${requestInfo.authRecord.collection().name} ${requestInfo.authRecord.id}`
);
e.record.set(
'updatedBy',
`${requestInfo.authRecord.collection().name} ${requestInfo.authRecord.id}`
);
} else if (requestInfo.admin !== null) {
if (!requestInfo.data.createdBy) {
e.record.set('createdBy', `${requestInfo.admin.tableName()} ${requestInfo.admin.id}`);
}
if (!requestInfo.data.updatedBy) {
e.record.set('updatedBy', `${requestInfo.admin.tableName()} ${requestInfo.admin.id}`);
}
} else {
e.record.set('createdBy', 'not authenticated');
e.record.set('updatedBy', 'not authenticated');
}
});
onRecordBeforeUpdateRequest((e) => {
const requestInfo = $apis.requestInfo(e.httpContext);
const currentRecord = $app.dao().findRecordById(e.record.collection().name, e.record.id);
// Update createdBy and updatedBy fields
if (requestInfo.authRecord !== null) {
// For regular users, overrides whatever their request had. Theses fields should not be editable by a regular user.
e.record.set('createdBy', currentRecord.get('createdBy'));
e.record.set(
'updatedBy',
`${requestInfo.authRecord.collection().name} ${requestInfo.authRecord.id}`
);
} else if (requestInfo.admin !== null) {
// For admins, only update the field if the request doesn't edit it
if (!requestInfo.data.createdBy) {
e.record.set('updatedBy', `${requestInfo.admin.tableName()} ${requestInfo.admin.id}`);
}
} else {
// For unauthenticated users, overrides whatever their request had. Theses fields should not be editable by a regular user.
e.record.set('createdBy', currentRecord.get('createdBy'));
e.record.set('updatedBy', 'not authenticated');
}
});
@IwateKyle
Copy link
Author

IwateKyle commented Sep 11, 2023

Thank you @Skylli202 for sharing this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment