Skip to content

Commit b0d9e41

Browse files
committed
feat: add runAction method for handling custom actions in AdminForth
1 parent cbb36cb commit b0d9e41

1 file changed

Lines changed: 80 additions & 1 deletion

File tree

adminforth/index.ts

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import {
2929
import {
3030
AdminForthFilterOperators,
3131
AdminForthDataTypes,
32-
AdminUser,
32+
AdminUser, ActionCheckSource
3333
} from './types/Common.js';
3434

3535
import AdminForthPlugin from './basePlugin.js';
@@ -815,6 +815,85 @@ class AdminForth implements IAdminForth {
815815
return { error: null };
816816
}
817817

818+
async runAction({
819+
resourceId,
820+
actionId,
821+
recordId,
822+
adminUser,
823+
extra = {},
824+
response,
825+
tr,
826+
}: {
827+
resourceId: string,
828+
actionId: string,
829+
recordId: string | number,
830+
adminUser: AdminUser,
831+
extra?: Record<string, any>,
832+
response?: any,
833+
tr?: any,
834+
}) {
835+
const resource = this.config.resources.find(
836+
(res) => res.resourceId === resourceId
837+
);
838+
839+
if (!resource) {
840+
return {
841+
ok: false,
842+
error: `Resource '${resourceId}' not found`,
843+
};
844+
}
845+
846+
const action = resource.options.actions?.find(
847+
(act) => act.id === actionId
848+
);
849+
850+
if (!action) {
851+
return {
852+
ok: false,
853+
error: `Action '${actionId}' not found`,
854+
};
855+
}
856+
857+
if (!action.action) {
858+
return {
859+
ok: false,
860+
error: `Action '${actionId}' has no action handler`,
861+
};
862+
}
863+
864+
if (typeof action.allowed === 'function') {
865+
const { allowedActions } = await interpretResource(
866+
adminUser,
867+
resource,
868+
{},
869+
ActionCheckSource.CustomActionRequest,
870+
this
871+
);
872+
873+
const execAllowed = await action.allowed({
874+
adminUser,
875+
standardAllowedActions: allowedActions,
876+
});
877+
878+
if (!execAllowed) {
879+
return {
880+
ok: false,
881+
error: `Action '${actionId}' not allowed`,
882+
};
883+
}
884+
}
885+
886+
return await action.action({
887+
recordId: String(recordId),
888+
adminUser,
889+
resource,
890+
adminforth: this,
891+
response: response as any,
892+
tr: tr as any,
893+
extra,
894+
});
895+
}
896+
818897
resource(resourceId: string): IOperationalResource {
819898
if (this.statuses.dbDiscover !== 'done') {
820899
if (this.statuses.dbDiscover === 'running') {

0 commit comments

Comments
 (0)