UNPKG

2.75 kBJavaScriptView Raw
1/**
2 * LokiJS JquerySyncAdapter
3 * @author Joe Minichino <joe.minichino@gmail.com>
4 *
5 * A remote sync adapter example for LokiJS
6 */
7
8/*jslint browser: true, node: true, plusplus: true, indent: 2 */
9
10(function (root, factory) {
11 if (typeof define === 'function' && define.amd) {
12 // AMD
13 define([], factory);
14 } else if (typeof exports === 'object') {
15 // CommonJS
16 module.exports = factory();
17 } else {
18 // Browser globals
19 root.lokiJquerySyncAdapter = factory();
20 }
21}(this, function () {
22
23 return (function (options) {
24 'use strict';
25
26 function JquerySyncAdapterError(message) {
27 this.name = "JquerySyncAdapterError";
28 this.message = (message || "");
29 }
30
31 JquerySyncAdapterError.prototype = Error.prototype;
32
33 /**
34 * this adapter assumes an object options is passed,
35 * containing the following properties:
36 * ajaxLib: jquery or compatible ajax library
37 * save: { url: the url to save to, dataType [optional]: json|xml|etc., type [optional]: POST|GET|PUT}
38 * load: { url: the url to load from, dataType [optional]: json|xml| etc., type [optional]: POST|GET|PUT }
39 */
40
41 function JquerySyncAdapter(options) {
42 this.options = options;
43
44 if (!options) {
45 throw new JquerySyncAdapterError('No options configured in JquerySyncAdapter');
46 }
47
48 if (!options.ajaxLib) {
49 throw new JquerySyncAdapterError('No ajaxLib property specified in options');
50 }
51
52 if (!options.save || !options.load) {
53 throw new JquerySyncAdapterError('Please specify load and save properties in options');
54 }
55 if (!options.save.url || !options.load.url) {
56 throw new JquerySyncAdapterError('load and save objects must have url property');
57 }
58 }
59
60 JquerySyncAdapter.prototype.saveDatabase = function (name, data, callback) {
61 this.options.ajaxLib.ajax({
62 type: this.options.save.type || 'POST',
63 url: this.options.save.url,
64 data: data,
65 success: callback,
66 failure: function () {
67 throw new JquerySyncAdapterError("Remote sync failed");
68 },
69 dataType: this.options.save.dataType || 'json'
70 });
71 };
72
73 JquerySyncAdapter.prototype.loadDatabase = function (name, callback) {
74 this.options.ajaxLib.ajax({
75 type: this.options.load.type || 'GET',
76 url: this.options.load.url,
77 data: {
78 // or whatever parameter to fetch the db from a server
79 name: name
80 },
81 success: callback,
82 failure: function () {
83 throw new JquerySyncAdapterError("Remote load failed");
84 },
85 dataType: this.options.load.dataType || 'json'
86 });
87 };
88
89 return JquerySyncAdapter;
90
91 }());
92}));
\No newline at end of file