ernest
Version:
Web framework for HTTP and HTTPS, using ExpressJS, Session, Mongo, Socket IO, Redis
813 lines (637 loc) • 18 kB
Markdown
# ernest
### Web framework for HTTP and HTTPS, using ExpressJS, Session, Mongo, Socket IO, Redis.
### NEW FEATURE : MANAGE YOUR MONGODB CODING ONLY ON CLIENT SIDE
### NEW FEATURE (2.1.8):BACKUP AND RESTORE MONGO DATABASE SYSTEMS
By cevr. For my son
Just create a public folder inside your project directory, put your files inside and do this:
```js
var Ernest = require('ernest');
new Ernest(null,__dirname + "/public").listen();
```
And your server is running on PORT:80 (http), loading your "public" folder.
If you are trying something bigger:
```js
new (require('ernest'))(db_name,iport,jsonlimt_mb,session_name,session_secret).
listen(otherorigins,key,cert,socketio_redis_port, isocketio_redis_server)
.LoadModules(function(app,dbc,messenger_io,ernest)
{
app.get("/hi",function(req,res,next) {res.send("Hi, Im Ernest"); });
}).Permission_Session(access_mongodb_collection).Static(ipublic).TextOnError('Access Denied').EnableCLI();
EXAMPLE with new Features:
new (require('ernest'))("ernest", 80,90,"str_key","str_secret")
.listen(true,null,null,6379,'localhost')
.Permission_Session("access")
.LoadModules(function(a,d,m,e)
{
a.get("/hi",function(req,res,next)
{
res.send(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Ubuntu:300" rel="stylesheet">
</head>
<body>
<center>
<h1>Hi, I am Ernest!</h1>
<h2>
<i class="fa fa-smile-o fa-6 fa-stack-2x" aria-hidden="true"></i>
</h2>
</center>
</body>
</html>
`);
});
})
.RewriteASRC("Find","search")
.EnableASR("/foxtrot")
.Static("./public")
.TextOnError('<!DOCTYPE html> <html> <body> <h1>Acceso Denegado</h1> <h1>Acceso Denegado</h1> </body> </html>')
.EnableCLI();
```
### Ernest
Creates a new instance of Ernest
#### db_name
Your mongo DB name(using mongojs name sintax).
By default no database.
#### ipublic
Your public folder.
By default the public folder inside ernest node_module.
On null set the public folder inside ernest node_module.
On "/" request = index.html
#### iport
The TCP Port you want the server to run(HTTP)
By default 80.
#### jsonlimt_mb
The max size of json body-parser urlencode
By default 90Mb
#### session_name
This is the name parameter for session (string)
By default the current date (string)
#### session_secret
this is the secret parameter for session (string)
By default the current date (string)
### listen
this function starts the service
#### allowothersite
If is set(as true) will allow cross site request
by default disabled
#### key
The path to the file ".pem" (key.pem) of ssl certificate. If is set, enables https.
By default is undefined and disable https.
#### cert
The path to the file ".crt" (server.crt) of ssl certificate. If kep aparameter is set, ermest looks for it and enables https.
By default is undefined and disable https.
#### socketio_redis_port
If is set, enables socket_io with redis for asincronic real time communication.
this parameter is the port where redis server is running.
Dont forget, for using this option you have to start your Redis Server and put these scripts on your header html files:
```js
<script src="/socket.io/socket.io.js"></script>
<script > var socket = io(); socket.on('disconnect', function () { alert('Server unreachable');});
```
By default is undefined and disable the socket_io system.
#### isocketio_redis_server
If socketio_redis_port is set, this parameter is the redis server ip. By default, is set as "localhost"
#### app
The express instance in which is running the server. You can use all the express methods (post,get, use, etc)
### messenger_io
Contains the function for emit messages through socket.io.
For emiting a new message you can use:
```js
//async
...
...
messenger_io.emit(type_msg,content);
```
type_msg: String. Word the socket.io on client side will be waiting for emition
content: String.String that receives socket.io on client side when type_msg is emitted
#### dbc
The mongo database controller ErnestDB which hace the following methods:
```js
//insert data
dbc.InsertInCollection (data,collec,function(e,d)
{
res.json({error:e,data:d});
})
//insert data and the user who inserted it;
dbc.InsertInCollectionBy (data,collec,insertedBy,function(e,d)
{
res.json({error:e,data:d});
});
//find one element by crit in collec
dbc.FindOneInCollection (crit,collec,function(e,d)
{
res.json({error:e,data:d});
});
//find all elements by crit in collec
dbc.FindInCollection (crit,collec,function(e,d)
{
res.json({error:e,data:d});
});
//find all and return the proyection(selected properties of elements in the array) array element in selected documents.
dbc.FindProyectInCollection (crit,proj,collec,function(e,d)
{
res.json({error:e,data:d});
});
//find one and return only the selected properties
dbc.FindOneInCollMostrar (crit,mostrar,collec,function(e,d)
{
res.json({error:e,data:d});
});
//find all and return only the selected properties
dbc.FindInCollecMostrar (crit,mostrar,collec,function(e,d)
{
res.json({error:e,data:d});
});
//update one document that matches crit in the collection collec
dbc.UpdateOneinCollec (crit,set,collec,function(e,d)
{
res.json({error:e,data:d});
});
//update one document that matches crit in the collection collec. Save the user in changedBy
dbc.UpdateOneinCollecBy (crit,set,collec,changedBy,function(e,d)
{
res.json({error:e,data:d});
});
//update many documents that match crit in the collection collec.
dbc.UpdateManyinCollec (crit,set,collec,function(e,d)
{
res.json({error:e,data:d});
});
//delete the documents that match the crit in the collection collec
dbc.DeleteFromCollection (crit,collec,function(e,d)
{
res.json({error:e,data:d});
});
//Find all documents that match the criteria crit, sorts the array of documents and limits the array
dbc.FindSortLimInCollect (crit,order,lim,collec,function(e,d)
{
res.json({error:e,data:d});
});
//Find all documents that match the criteria crit, sorts the array of documents and limits the array
dbc.FindSortInCollection (crit,order,collec,function(e,d)
{
res.json({error:e,data:d});
});
//Executes an aggregation on collect
dbc.AggregatetoArray (agg_arry,collec,function(e,d)
{
res.json({error:e,data:d});
});
//Return all documents distincs on query that match the crit
dbc.GetDistincts (crit,query,collec,function(e,d)
{
res.json({error:e,data:d});
});
//Return all collection names
dbc.getCollectionNames (function(e,d)
{
res.json({error:e,data:d});
});
//Return the collection mongojs obj
dbc.GetCollection (collec)
//Renames the collection
dbc.RenameCollection (oldcollec,newcollec,function(e,d)
{
res.json({error:e,data:d});
});
//Creates the collection collec
dbc.CreateCollection (collec,function(e,d)
{
res.json({});
});
//Drops the collection collec
dbc.DropCollection (collec,function(e,d)
{
res.json({error:e,data:d});
});
//Empty the collection collec
dbc.EmptyCollection (collec,function(e,d)
{
res.json({error:e,data:d});
});
//Erase the collections that begins with erase value
dbc.EraseCollections (erase,function(e,d)
{
res.json({error:e,data:d});
});
//Creates a clone of the collection src, with the name dst
dbc.CloneCollection (src,dst,function(e,d)
{
res.json({error:e,data:d});
});
```
####access_mongodb_collection
Collection where users are stored.
## this version with CLI
### .EnableCLI();
Show Erenst CLI in console.
### CLI Commands
#### addUser
Add a new user to your login web system.(user, password, propiertis in json format : {"name": "john doe", "age":34, level:33})
#### deleteUser
Delete a user to your login web system
#### showUser
Show user info
#### status
Show Ernest info (port - http / https)
#### pid
Show Current Ernest PID procces
#### db
Show current Mongo DB
#### setdb
Set a Mongo DB
#### updateUserPassword
Update user password
#### updateUserProperties
Update User properties
#### addPagetoUser
Add permission for user access to the a specific page.
####addPagestoUser
Add permission for user access to the a many pages, separates by ",".
#### removePageUser
Remove permission for user access to the a specific page.
#### createCollection
Create a collection in the current Mongo Db.
#### deleteCollection
Delete a collection in the current Mongo Db.
#### collectionExist
Show if collection exits in the current Mongo DB.
#### Collections
Show all collections in the current Mongo DB.
#### ListPublicFiles
Show the files in public folder
#### CopyPublicFile
Copy one file in public folder, with other name(example: template file) inside public folder.
#### DB_Backup
Create Current Ernest DB Backup. Exports DB to a specific tar.gz file
#### DB_Restore
Restore Ernest DB from Backup. Imports DB from a specific tar.gz file
#### man
Show Ernest command info.
#### clear
Clear Ernest CLI.
#### exit
Stop Ernest an exit Ernest CLI.
## New Feature
###EnableASR(asr_url)
Enables Ernest Automatic Server Response.Using asr_url for reciving ASR commands.If is undefined by default is "/~edbc". Read more in the section ASR - Automatic Server Response
```js
//on serverside usinf "/foxtrot" as ASR url.
ernest.EnableASR("/foxtrot")
```
### RewriteASRC(native_command,newname)
Redefine ASR Command as security method, So you can rename ASR command like "Find" to "search"
```js
//on serverside
ernest.RewriteASR("Find","search")
```
, and in your client side js file you will be able to call it like this:
```js
var c = {};
c.command = "search";
c.collec = "products";
c.crit = {};
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
Read more in the section ASR - Automatic Server Response
#ASR - Automatic Server Response
New Ernest Automatic Server Response system, that allows you to interact with your mongodb collections without coding on serverside. Code only clientside.
##ASR Commands
Using "/foxtrot" (for example) as the ASR url, you can use the next commands
###Insert
insert data in collection
####Usage on client side
```js
var c = {};
c.command = "Insert";
c.collec = "products";
c.data = {"name":"linux"};
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###InsertBy
insert data in collection and the user who inserted it
####Usage on client side
```js
var c = {};
c.command = "InsertBy";
c.collec = "products";
c.data = {"name":"linux_unix"};
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###FindOne
find one element by criteria crit in collec
####Usage on client side
```js
var c = {};
c.command = "FindOne";
c.collec = "products";
c.crit = {name:"linux"};
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Find
find all elements by crit in collec
####Usage on client side
```js
var c = {};
c.command = "Find";
c.collec = "products";
c.crit = {};
c.crit['name'] = {'$regex' : 'li' };
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###FindProyect
find all and return the proyection(selected properties of elements in the array) array element in selected documents.
####Usage on client side
```js
var c = {};
c.command = "FindProyect";
c.collec = "products";
c.crit = {};
c.proy = {'_id' : 0, 'name':1};
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###FindOneShow
find one and return only the selected properties
####Usage on client side
```js
var c = {};
c.command = "FindOneShow";
c.collec = "products";
c.crit = {};
c.show = {'_id' : 0, 'name':1};
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###FindShow
find all and return only the selected properties
####Usage on client side
```js
var c = {};
c.command = "FindShow";
c.collec = "products";
c.crit = {};
c.show = {'_id' : 0, 'name':1};
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Update
update one document that matches crit in the collection collec
####Usage on client side
```js
var c = {};
c.command = "Update";
c.collec = "products";
c.crit = {"name":"linux_unix"};
c.set["$set"] = {};
c.set["$set"]["description"] = "operative system";
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###UpdateBy
update one document that matches crit in the collection collec. Save the user in changedBy
####Usage on client side
```js
var c = {};
c.command = "UpdateBy";
c.collec = "products";
c.crit = {"name":"linux_unix"};
c.set["$set"] = {};
c.set["$set"]["description"] = "operative system";
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###UpdateMany
update many documents that match crit in the collection collec.
####Usage on client side
```js
var c = {};
c.command = "UpdateMany";
c.collec = "products";
c.crit = {};
c.crit['name'] = {'$regex' : 'li' };
c.set["$set"] = {};
c.set["$set"]["description"] = "operative system";
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###DeleteFrom
delete the documents that match the crit in the collection collec
####Usage on client side
```js
var c = {};
c.command = "DeleteFrom";
c.collec = "products";
c.crit = {"name":"linux"};
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###FindSortLim
Find all documents that match the criteria crit, sorts the array of documents and limits the array
####Usage on client side
```js
var c = {};
c.command = "FindSortLim";
c.collec = "products";
c.crit = {};
c.order = {_id : -1};
c.lim = 1;
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###FindSort
Find all documents that match the criteria crit, sorts the array of documents and limits the array
####Usage on client side
```js
var c = {};
c.command = "FindSort";
c.collec = "products";
c.crit = {};
c.order = {_id : -1};
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Aggregate
Executes an aggregation on collect
####Usage on client side
```js
var c = {};
c.command = "Aggregate";
c.collec = "products";
c.crit = {};
c.aggr = [{$unwind:"$field"}, {$unwind:'$field.children'}, {$unwind:'$field.children.children'}, {$match: {'field.children.children.link': curl, 'user':'admin' } }, {$project: {'field.children.children.link':1, 'field.children.children.name':1, '_id':0, 'user':1, 'field.children.children.access':1 } }];
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Distincts
Return all documents distincs on query that match the crit
####Usage on client side
```js
var c = {};
c.command = "Distincts";
c.collec = "products";
c.crit = "name";
c.query = {};
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Names
Return all collection names. You most send one collection name
####Usage on client side
```js
var c = {};
c.command = "Names";
c.collec = "products";
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Exist
Return true if the collection exist
####Usage on client side
```js
var c = {};
c.command = "Exist";
c.collec = "products";
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Rename
Renames the collection
####Usage on client side
```js
var c = {};
c.command = "Rename";
c.collec = "products";
c.newcollec = "opertive_systems";
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Create
Creates the collection collec
####Usage on client side
```js
var c = {};
c.command = "Create";
c.collec = "new_products";
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Drop
Drops the collection collec
####Usage on client side
```js
var c = {};
c.command = "Drop";
c.collec = "products";
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Empty
Empty the collection collec
####Usage on client side
```js
var c = {};
c.command = "Empty";
c.collec = "products";
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Erase
Erase the collections that begins with beginwith value. You have to send one collection name
####Usage on client side
```js
var c = {};
c.command = "Erase";
c.collec = "products";
c.beginwith = "prod";
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
###Clone
Creates a clone of the collection src, with the name newcollect value
####Usage on client side
```js
var c = {};
c.command = "Clone";
c.collec = "products";
c.newcollec = "products_copy";
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
```
## EXAMPLE WITH ANGULARJS ON CLIENTCLIENT SIDE
```js
$scope.LoadProducts = function()
{
var c = {};
c.command = "search";
c.collec = "products";
c.crit = {};
$http.post("/foxtrot",c).then(function(r)
{
console.log(r.data);
});
};
```
## README in edition