Created
September 11, 2023 03:35
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you @Skylli202 for sharing this.