SlashDB
angular-slashdb - AngularJS bindings toSlashDB 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
- Running angular-slashdb example application
-
General description
- Injecting angularSlashDB into your app
- Injecting and configuring slashDBProvider
-
Injecting slashDB service
- Example slashDB service usage
-
slashDB utility methods usage
- get
- post
- put
- delete
- escapeValue
- subscribeLogin and notifyLogin
- subscribeLogout and notifyLogout
- subscribeSettingsChange and notifySettingsChange
- getSettings
- login
- logout
- isAuthenticated
- uploadLicense
- loadModel and unloadModel
- getDBDefs and getDBDef
- createDBDef, updateDBDef and deleteDBDef
- getUserDefs and getUserDef
- createUserDef, updateUserDef and deleteUserDef
- getQueryDefs and getQueryDef
- createQueryDef, updateQueryDef and deleteQueryDef
- getQueries and executeQuery
- Copyright
Install angular-slashdb
Dependencies
- SlashDB >= 0.9.7
- AngularJS >= 1.5.7 and < 2.0
Bower
Usingbower install angular-slashdb
NPM
Usingnpm install angular-slashdb
From source
You can also build from TypeScript source code.
Clone repo:
git clone git@github.com:SlashDB/angular-slashdb.git
Setup environment:
cd angular-slashdb
npm install -g
typings install
Building angular-slashdb:
npm run build
Now you can include ./dist/angular-slashdb.js in your project.
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
Node
install http-server
npm install http-server -g
then, while in example directory, you can simply
http-server -p 8000
General description
Injecting angularSlashDB
var exampleApp = angular.module('exampleApp', ['angularSlashDB']);
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');
}])
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
}
}
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');
}])
setCacheData
Sets cacheData caching flag.
exampleApp.config(['slashDBProvider', function (slashDBProvider) {
// by default set to true
slashDBProvider.setCacheData(false);
}])
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'});
}])
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);
}])
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({});
}])
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;
}])
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 {};
}])
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 {};
}])
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 {};
}])
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 {};
}])
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 {};
}])
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 {};
}])
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 {};
}])
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 {};
}])
getSettings
Fetches 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.getSettings();
return {};
}])
login
Perform a login request.
exampleApp.service('myService', ['slashDB', function (slashDB) {
slashDB.login(); // returns a Promise for further use
return {};
}])
logout
Perform a logout request.
exampleApp.service('myService', ['slashDB', function (slashDB) {
slashDB.logout(); // returns a Promise for further use
return {};
}])
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 {};
}])
uploadLicense
Uploads licence file data to slashDB instance.
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);
}
}
})
loadModel and unloadModel
- loadModel - connects a given database on the backend
- unloadModel - disconnects a given database on the backend
exampleApp.service('myService', ['slashDB', function (slashDB) {
slashDB.loadModel(); // returns a Promise for further use
slashDB.unloadModel(); // returns a Promise for further use
return {};
}])
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 {};
}])
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_encoding': 'utf-8',
'owners': ['admin'],
'execute': [],
'creator': 'admin',
'read': [],
'db_type': 'sqllite3',
'autoload': false,
'write': [];
'connect_status': '',
'connection': '',
'foreign_keys': {},
'sysuser': {'dbuser': 'admin', 'dbpass': 'admin'},
'db_schema': '',
'offline': false,
'alternate_key': {},
'excluded_columns': {},
'desc': '';
};
// create a new DB definition
slashdb.createDBDef('newDBDef', 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 {};
}])
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 {};
}])
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 = {
'userdef': ['newUserDef'],
'api_key': 'somekey',
'name': 'newQueryDef',
'creator': 'admin',
'edit': [];
'dbdef': ['someDBDef'];
'querydef': [];
'databases': {'dbuser': 'me', 'dbpass': 'mypass'},
'password': 'mypass';
'email': 'me@me.com';
'view': '';
};
// create a new User definition
slashdb.createDBDef('newUserDef', 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 {};
}])
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 {};
}])
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 = {
'owners': ['me'],
'viewable': true,
'creator': 'me',
'read': [],
'database': 'someDB',
'execute': [],
'write': [],
'sqlstr': '',
'executable': true,
'columns': 'Name'
};
// create a new Query definition
slashdb.createDBDef('newQueryDef', newQueryDef).then(function() {
console.log('new query def created!');
});
// update definition
slashdb.updateDBDef('newQueryDef', {'email': 'newMe@me.com'});
// delete definition
slashdb.deleteDBDef('newQueryDef').then(function() {
console.log('it is gone!');
});
return {};
}])
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 {};
}])