Dynamic Hooks
Dynamic Hooks are more flexible than Java Hooks, because they can be changed at run-time and can run per document if needed, but are slower than Java Hooks. Look at Hooks for more information.
To execute hooks against your documents, let your classes to extend OTriggered
base class. Then define a custom property for the event you’re interested on. The available events are:
onBeforeCreate
, called before creating a new documentonAfterCreate
, called after creating a new documentonBeforeRead
, called before reading a documentonAfterRead
, called after reading a documentonBeforeUpdate
, called before updating a documentonAfterUpdate
, called after updating a documentonBeforeDelete
, called before deleting a documentonAfterDelete
, called after deleting a document
Dynamic Hooks can call:
- Functions, written in SQL, Javascript or any language supported by OrientDB and JVM
- Java static methods
Class level hooks
Class level hooks are defined for all the documents that relate to a class. Below is an example to setup a hook that acts at class level against Invoice documents.
CREATE CLASS Invoice EXTENDS OTriggered
ALTER CLASS Invoice CUSTOM onAfterCreate=invoiceCreated
Now let’s create the function invoiceCreated
in Javascript that prints in the server console the invoice number created.
CREATE FUNCTION invoiceCreated "print('\\nInvoice created: ' + doc.field('number'));" LANGUAGE Javascript
Now try the hook by creating a new Invoice
document.
INSERT INTO Invoice CONTENT { number: 100, notes: 'This is a test' }
And this will appear in the server console:
Invoice created: 100
Document level hook
You could need to define a special action only against one or more documents. To do this, let your class to extend OTriggered
class.
Example to execute a trigger, as Javascript function, against an existent Profile class, for all the documents with property account = 'Premium'
. The trigger will be called to prevent deletion of documents:
ALTER CLASS Profile SUPERCLASS OTriggered
UPDATE Profile SET onBeforeDelete = 'preventDeletion' WHERE account = 'Premium'
And now let’s create the preventDeletion()
Javascript function.
CREATE FUNCTION preventDeletion "throw new java.lang.RuntimeException('Cannot delete Premium profile ' + doc)" LANGUAGE Javascript
And now test the hook by trying to delete a Premium
account.
DELETE FROM #12:1
java.lang.RuntimeException: Cannot delete Premium profile profile#12:1{onBeforeDelete:preventDeletion,account:Premium,name:Jill} v-1 (<Unknown source>#2) in <Unknown source> at line number 2