Skip to content

Instantly share code, notes, and snippets.

@troyk
Created March 20, 2012 16:17
Show Gist options
  • Select an option

  • Save troyk/2137798 to your computer and use it in GitHub Desktop.

Select an option

Save troyk/2137798 to your computer and use it in GitHub Desktop.
plv8 example
CREATE OR REPLACE FUNCTION dbo.contacts(account_id integer, user_id text, sync text) RETURNS text AS $$
if (typeof DBO !== 'function') executeSql('SELECT dbo.init();');
var Contacts = DBO.Contacts || DBO.extend('Contacts',{
stiContact: function stiContact(contact) {
if (contact.type === 'company') {
delete contact.first_name;
delete contact.last_name;
delete contact.title;
}
return contact;
},
stiContactInfo: function stiContactInfo(contact, info) {
switch(info.type) {
case 'phone':
if (!contact.phones) contact.phones = [];
contact.phones.push({number: info.address, label: info.label});
break;
}
},
save: function save(contact, newRecord) {
var contacts_info = contact.contacts_info || [];
// infos
delete contact.contacts_info;
// readonly fields
delete contact.created_at;
delete contact.created_by;
// newRecord
if (newRecord) contact.created_by = this.user_id;
contact = this.stiContact(this.upsert('contacts',contact,'*'));
for (var i=0,iLen=contacts_info.length; i<iLen; i++) this.stiContactInfo(contact,this.upsert('contacts_info',contacts_info[i],'*'));
return contact;
},
find: function find(options) {
var contact, contacts;
if (options.id) {
contact = this.stiContact(this.findById('contacts',options.id));
}
}
});
return JSON.stringify(new Contacts(account_id,user_id,sync));
// '{"method":"create","data":{"type":"person","name":"Troy Kruthoff","first_name":"Troy","last_name":"Kruthoff","contacts_info":[{"type":"phone","address":"916-555-1212"}]}}'
$$ LANGUAGE plv8 IMMUTABLE STRICT;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment