@slashdb/angular-slashdb

0.0.3 • Public • Published

angular-slashdb - AngularJS bindings to SlashDB

=========

SlashDB automatically creates REST APIs on top of traditional databases for reading and writing by authorized applications without the need of SQL queries. Angular-slashdb is a small plug-in, allowing you to use SlashDB features more easily in your AngularJS app. Together they allow developers to avoid tedious work and focus on application features that matter.

Usage example

var exampleApp = angular.module('exampleApp', ['angularSlashDB'])
    .config(['slashDBProvider', function (slashDBProvider) {
        // set endpoint to your slashDB instance
        slashDBProvider.setEndpoint('http://localhost:6543');
    }])
    .service('myService', ['slashDB', function (slashDB) {
        var defaultData = [{ 'Name': 'AC/DC' }, { 'Name': 'Buddy Guy' }];
        var model = { data: defaultData };

        // update initial model data
        slashDB.get('/db/Chinook/Artist.json').then(function(response) {
                model.data = response.data;
            });
        });

        return model;
    }]);

see example application folder for more details.

Table of contents

Install angular-slashdb

Dependencies

  • SlashDB >= 0.9.7
  • AngularJS >= 1.5.7 and < 2.0

Back to top

Using Bower

bower install angular-slashdb

Back to top

Using NPM

npm install angular-slashdb

Back to top

From source

You can also build from TypeScript source code.

Clone repo:

git clone git@github.com:SlashDB/angular-slashdb.git

Back to top

Setup environment:

cd angular-slashdb
npm install -g
typings install

Back to top

Building angular-slashdb:

npm run build

Now you can include ./dist/angular-slashdb.js in your project.

Back to top

Running angular-slashdb example application

You can directly open example/index.html in your browser of choice or use one of the following methods.

Python

while in example directory

using python3

python -m http.server 8000

or python2

python -m SimpleHTTPServer 8080

Back to top

Node

install http-server

npm install http-server -g

then, while in example directory, you can simply

http-server -p 8000

Back to top

General description

Back to top

Injecting angularSlashDB

var exampleApp = angular.module('exampleApp', ['angularSlashDB']);

Back to top

Injecting slashDBProvider

Configure it so that it points to your SlashDB instance i.e.:

exampleApp.config(['slashDBProvider', function (slashDBProvider) {
    // set endpoint to your slashDB instance
    slashDBProvider.setEndpoint('http://localhost:6543');
}])

Back to top

Default angular-slashdb configuration:

config = {
    endpoint: '',              // default slashDB endpoint, it's required to set this to a proper value
    cacheData: false,          // determines if cached data should be used
    apiKeys: {},               // hold optional API keys
    httpRequestConfig: {       // user provided request config
        headers: {},           // holds user provided request headers
        params: {},            // holds user provided request params i.e. {depth: 1, sort: LastName}
        withCredentials: true  // determines if cookie based authentication should be used
    }
}

Back to top

slashDBProvider methods usage

You can set slashDBProvider fields by hand, but it's more convenient and safer to use methods provided by us.

setEndpoint

Sets default endpoint.

exampleApp.config(['slashDBProvider', function (slashDBProvider) {
    // by default this is set to '' so you'll need to set this to sane value
    slashDBProvider.setEndpoint('http://localhost:6543');
}])

Back to top

setCacheData

Sets cacheData caching flag.

exampleApp.config(['slashDBProvider', function (slashDBProvider) {
    // by default set to true
    slashDBProvider.setCacheData(false);
}])

Back to top

setHeaders

Sets default request headers of your choice.

exampleApp.config(['slashDBProvider', function (slashDBProvider) {
    // every request made will have 'Accept=application/json' header set
    slashDBProvider.setHeaders({'Accept': 'application/json'});
}])

Back to top

setWithCredentials

Sets flag determining what method of authentication should be used.

  • true - angular-shashdb will use cookie based authentication
  • false - user API keys will be used
exampleApp.config(['slashDBProvider', function (slashDBProvider) {
    slashDBProvider.setWithCredentials(false);
}])

Back to top

setAPIKeys

Sets API authentication request keys - provided by your SlashDB admin.

Important: this will be only used after the (slashDB service) login method has been used.

exampleApp.config(['slashDBProvider', function (slashDBProvider) {
    // 'APIKey' and 'otherKey' are examples - contact your SlashDB admin for the real thing
    // setting this will also set setWithCredentials to false
    // and every get request will have APIKey=1234&otherKey=4321 query sting attached automatically
    slashDBProvider.setAPIKeys({'APIKey': '1234', 'otherKey': '4321'});
    // using setAPIKeys with an empty object will remove all previously set API keys and set setWithCredentials to true
    // so that the default authentication behavior of using cookies will be restored
    slashDBProvider.setAPIKeys({});
}])

Back to top

Injecting slashDB service

Example slashDB service usage

exampleApp.service('myService', ['slashDB', function (slashDB) {
    var defaultData = [{ 'Name': 'AC/DC' }, { 'Name': 'Buddy Guy' }];
    var model = { data: defaultData };

    // update initial model data
    slashDB.get('/db/Chinook/Artist.json').then(function(response) {
            model.data = response.data;
        });
    });

    return model;
}])

Back to top

slashDB utility methods usage

get

Wrapper around angulars $http.get.

exampleApp.service('myService', ['slashDB', function (slashDB) {
    // by passing an request config object, it's possible to control request in a fine grained manner
    // passing true as the 3rd param, will omit using cache and re-download data
    // passing false as the 4th function param, it's possible to treat returned data as a single value, rather than an array of values (the default)
    // returns a Promise for further use
    var myRequestCofig = {
        headers: { 'Accept': 'application/json' },
        params: { count: '' }
    };

    slashDB.get('/db/Chinook/Artist.json', true, myRequestCofig, false).then(function(response) {
            console.log('data received!');
        });
    });
    return {};
}])

Back to top

post

Wrapper around angulars $http.post.

exampleApp.service('myService', ['slashDB', function (slashDB) {
    // by passing an request config object, it's possible to control request in a fine grained manner
    // returns a Promise for further use
    var myRequestCofig = {
        headers: { 'Accept': 'application/json' }  // the default
    };

    var newRecordData = { 'Name': 'Killswitch Engage' };
    slashDB.post('/db/Chinook/Artist.json', newRecordData, myRequestCofig, false).then(function(response) {
            console.log('new object created!');
        });
    });
    return {};
}])

Back to top

put

Wrapper around angulars $http.put.

exampleApp.service('myService', ['slashDB', function (slashDB) {
    // by passing an request config object, it's possible to control request in a fine grained manner
    // returns a Promise for further use
    var updateRecordData = { 'Email': 'Joe@gmail.com' };
    slashDB.put('/db/Chinook/Customer/CustomerId/1.json', updateRecordData, {}, false).then(function(response) {
            console.log('object updated!');
        });
    });
    return {};
}])

Back to top

delete

Wrapper around angulars $http.delete.

exampleApp.service('myService', ['slashDB', function (slashDB) {
    // by passing an request config object, it's possible to control request in a fine grained manner
    // returns a Promise for further use
    slashDB.delete('/db/Chinook/Customer/CustomerId/1.json').then(function(response) {
            console.log('object deleted!');
        });
    });
    return {};
}])

Back to top

escapeValue

Replaces characters using mapping defined in SlashDB settings.

exampleApp.service('myService', ['slashDB', function (slashDB) {
    var escapedValue = slashDB.escapeValue('AC/DC');  // will return AC__DC if SlashDB is cofigured to substitute '/' with '__'
    return {};
}])

Back to top

subscribeLogin and notifyLogin

  • subscribeLogin - subscribe to a login event
  • notifyLogin - emmit a login event
exampleApp.service('myService', ['slashDB', function (slashDB) {
    slashDB.subscribeLogin(config.scope, function () {
        console.log('an `slashdb-service-login-event` event has occurred');
    });

    slashDB.notifyLogin();  // this will emit `slashdb-service-login-event` event and execute the callback function
    return {};
}])

Back to top

subscribeLogout and notifyLogout

  • subscribeLogout - subscribe to a logout event
  • notifyLogout - emmit a logout event
exampleApp.service('myService', ['slashDB', function (slashDB) {
    slashDB.subscribeLogout(config.scope, function () {
        console.log('an `slashdb-service-settings-update-event` event has occurred');
    });

    slashDB.notifyLogout();  // this will emit `slashdb-service-settings-update-event` event and execute the callback function
    return {};
}])

Back to top

subscribeSettingsChange and notifySettingsChange

  • subscribeSettingsChange - subscribe to a settings change event
  • notifySettingsChange - emmit a settings change event
exampleApp.service('myService', ['slashDB', function (slashDB) {
    slashDB.subscribeSettingsChange(config.scope, function () {
        console.log('an `slashdb-service-settings-update-event` event has occurred');
    });

    slashDB.notifySettingsChange();  // this will emit `slashdb-service-settings-update-event` event and execute the callback function
    return {};
}])

Back to top

setupSettings

Fetches and stores settings object from SlashDB instance.

exampleApp.service('myService', ['slashDB', function (slashDB) {
    // this will get and/or update slashDB settings data, emit an `slashdb-service-settings-update-event`, and return a Promise for further use
    slashDB.setupSettings();
    return {};
}])

Back to top

login

Perform a login request.

exampleApp.service('myService', ['slashDB', function (slashDB) {
    slashDB.login('your-slasdb-user-name', 'your-slasdb-password');  // returns a Promise for further use
    return {};
}])

Back to top

logout

Perform a logout request.

exampleApp.service('myService', ['slashDB', function (slashDB) {
    slashDB.logout();  // returns a Promise for further use
    return {};
}])

Back to top

isAuthenticated

Checks if the user is authenticated.

exampleApp.service('myService', ['slashDB', function (slashDB) {
    if (slashDB.isAuthenticated()); {
        console.log('doing something');
    } else {
        console.log('doing something else');
    }
    return {};
}])

Back to top

uploadLicense

Uploads licence file data to slashDB instance. By default license is validated and installed in SlashDB. If second (Boolean) argument is set true then license data will be only validated (license won't be installed).

exampleApp.component('myComponent', {
    template: '<form name="form" ng-submit="$ctrl.submit()">' +
                '<input type="file" ng-model="$ctrl.myModel.license" name="license" />' +
                '<button type="submit" class="btn btn-primary">Send license</button>' +
              '</form>',
    controller: function ($element, slashDB) {
        var ctrl = this;
        ctrl.submit = function(e) {
            var licenseFile = $element[0].childNodes[0].childNodes[0].files[0]);
            slashDB.uploadLicense(licenseFile, false);
        }
    }
})

Back to top

dbOn and dbOff

  • dbOn - connects a given database on the backend
  • dbOff - disconnects a given database on the backend
exampleApp.service('myService', ['slashDB', function (slashDB) {
    slashDB.dbOff('testDB');  // returns a Promise for further use
    slashDB.dbOn('testDB');   // returns a Promise for further use
    return {};
}])

Back to top

toggleDB

Toggles given DB-s state i.e. On -> Off, and vice versa.

exampleApp.service('myService', ['slashDB', function (slashDB) {
    slashDB.getDBDefs.then(function () {
        var dbDef = SlashDB.dbDefs['myDB'];
        slashDB.toggleDB(dbDef);  // returns a Promise for further use
    });
}])

Back to top

getDBDefs and getDBDef

  • getDBDefs - perform a request for definitions for all databases
  • getDBDef - perform a request for definition for a given database
exampleApp.service('myService', ['slashDB', function (slashDB) {
    // get all DB definition
    slashDB.getDBDefs(true);       // returns a Promise for further use, passing true will omit using cache and re-download data
    // get just a selected DB definition
    slashDB.getDBDef('Customer');  // returns a Promise for further use
    return {};
}])

Back to top

createDBDef, updateDBDef and deleteDBDef

  • createDBDef - create a new database definition
  • updateDBDef - update a database definition
  • deleteDBDef - delete a database definition
exampleApp.service('myService', ['slashDB', function (slashDB) {
    // newDBDef might have a diffrent 'shape' on your version of SlashDB
    var newDBDef = {
        'db_id': 'newDBDef',
        'db_encoding': 'utf-8',
        'owners': [
            'admin'
        ],
        'creator': 'admin',
        'read': [],
        'editable': true,
        'db_type': 'sqlite',
        'executable': true,
        'autoload_user': {
            'dbuser': 'admin',
            'dbpass': 'admin'
        },
        'autoload': true,
        'viewable': true,
        'write': [],
        'connection': '/my/path/mydb.sqlite',
        'foreign_keys': {},
        'execute': [],
        'db_schema': null,
        'offline': false,
        'alternate_key': {},
        'excluded_columns': {},
        'desc': 'my sqlite db'
    };
    // create a new DB definition
    slashdb.createDBDef(newDBDef).then(function() {
        console.log('new db def created!');
    });
    // update definition
    slashdb.updateDBDef('newDBDef', {'owners': ['me', 'joe']});
    // delete definition
    slashdb.deleteDBDef('newDBDef').then(function() {
        console.log('it is gone!');
    });
    return {};
}])

Back to top

getUserDefs and getUserDef

  • getUserDefs - perform a request for definitions for all users
  • getUserDef - perform a request for definition for a given user
exampleApp.service('myService', ['slashDB', function (slashDB) {
    // get all User definition
    slashDB.getUserDefs(true);    // returns a Promise for further use, passing true will omit using cache and re-download data
    // get just a selected User definition
    slashDB.getUserDef('admin');  // returns a Promise for further use
    return {};
}])

Back to top

createUserDef, updateUserDef and deleteUserDef

  • createUserDef - create a new user definition
  • updateUserDef - update a user definition
  • deleteUserDef - delete a user definition
exampleApp.service('myService', ['slashDB', function (slashDB) {
    // newUserDef might have a diffrent 'shape' on your version of SlashDB
    var newUserDef = {
        'user_id': 'newUserDef',
        'userdef': [],
        'api_key': 'somekey',
        'name': 'newQueryDef',
        'creator': 'admin',
        'edit': [];
        'dbdef': ['create', 'view']; // user can view and create DB definitions
        'querydef': [];              
        'databases': {
            'Chinook': {
                'dbuser': 'me',
                'dbpass': 'mypass'
            }
        },
        'password': 'mypass';
        'email': 'me@me.com';
        'view': []
    };
    // create a new User definition
    slashdb.createDBDef(newUserDef).then(function() {
        console.log('new user def created!');
    });
    // update definition
    slashdb.updateDBDef('newUserDef', {'email': 'newMe@me.com'});
    // delete definition
    slashdb.deleteDBDef('newUserDef').then(function() {
        console.log('it is gone!');
    });
    return {};
}])

Back to top

getQueryDefs and getQueryDef

  • getQueryDefs - perform a request for definitions for all queries
  • getQueryDef - perform a request for definition for a given query
exampleApp.service('myService', ['slashDB', function (slashDB) {
    // get all Query definition
    slashDB.getQueryDefs(true);                // returns a Promise for further use, passing true will omit using cache and re-download data
    // get just a selected Query definition
    slashDB.getQueryDef('customers-in-city');  // returns a Promise for further use
    return {};
}])

Back to top

createQueryDef, updateQueryDef and deleteQueryDef

  • createUserDef - create a new query definition
  • updateUserDef - update a query definition
  • deleteUserDef - delete a query definition
exampleApp.service('myService', ['slashDB', function (slashDB) {
    // newQueryDef might have a diffrent 'shape' on your version of SlashDB
    var newQueryDef = {
        'query_id': 'newQueryDef',
        'creator': 'me',
        'read': ['me'],
        'database': 'someDB',
        'execute': ['me'],
        'write': ['me'],
        "http_methods": {
            "GET": true,
        },
        'sqlstr': 'select * from Customer',
        'desc': 'new query def'
    };
    // create a new Query definition
    slashdb.createDBDef(newQueryDef).then(function() {
        console.log('new query def created!');
    });
    // update definition
    slashdb.updateDBDef('newQueryDef', {'desc': 'different desc'});
    // delete definition
    slashdb.deleteDBDef('newQueryDef').then(function() {
        console.log('it is gone!');
    });
    return {};
}])

Back to top

getQueries and executeQuery

  • getQueries - perform a request for a list available SQL Pass-thru queries
  • executeQuery - execute SQL Pass-thru query
exampleApp.service('myService', ['slashDB', function (slashDB) {
    slashDB.getQueries(true).then(function(response) {  // returns a Promise for further use, passing true will omit using cache and re-download data
        var data = response.data;                       // i.e. response.data = {
                                                        //   "customers-in-city": {
                                                        //       "desc": "Customer phone list by city (i.e. London)",
                                                        //       "parameters": [
                                                        //           "city"
                                                        //       ],
                                                        //       "database": "Chinook"
                                                        //   },
                                                        //   "sales-by-year": {
                                                        //       "desc": "Sales Total by Year",
                                                        //       "parameters": [],
                                                        //       "database": "Chinook"
                                                        //   }
                                                        // }
        // lets use 'customers-in-city' with 'city' parameter and 'Chicago' as the city
        slashDB.executeQuery('/customers-in-city/city/Chicago.json').then(function(response) {
            console.log('a Pass-thru query is done!');
        });
    });
    return {};
}])

Back to top

Copyright

Copyright (C) 2016, VT Enterprise LLC. SlashDB and angular-slashdb are products of VT Enterprise LLC.

Back to top

Package Sidebar

Install

npm i @slashdb/angular-slashdb

Weekly Downloads

0

Version

0.0.3

License

MIT

Unpacked Size

1.98 MB

Total Files

23

Last publish

Collaborators

  • mdob
  • jonh_slashdb
  • agilevic