All examples are optimized for Total.js +4
version.
- first you have to install Total.js framework
$ npm install total4
- then run each example like this:
$ cd workers
$ node index.js
Total.js examples
Hi Peter,
I have this weird problem with websocekts:
WHAT WORKS:
The client websocket connects to the server as expected. The server receives the websocket connection request successfully and establishes the connection. Then the client and server start communicating smoothly and with no problem.
WHAT DOES NOT WORK:
However it seems that total.js
never sends the final ACK for the browser's upgrade request so that the browser (tested on Chrome and Firefox) keeps the connection in pending
state and thinks the connection request has timed out and closes the connection after a while. The connection times out after 2 minutes on Chrome. So the websocket connection only lasts for two minutes and closes unexpectedly.
HOW TO REPRODUCE:
1- download the angularjs-websocket
example from the tota.js's examples repo,
2- modify/add the following lines at the end of default.js
controller:
self.on('close', function(client) {
console.log(new Date() + ': SERVER: onclose');
refresh();
});
self.on('open', function(client) {
console.log(new Date() + ': SERVER: onopen');
});
3- run the project. Please pay attention to the pending
state on dev tool's network tab:
For many of the examples, it would be nice if there was a live online demo showing the results so developers could see the results without having to download the example. They could have the code open in one window and the live demo open in another window and see the two side by side.
For example, in the bootstrap
example, the readme.md
could include a link to http://examples.totaljs.com/bootstrap/
so the developer can see what the end result looks like in the browser.
The blocks
example is another one where a demo would be useful, as the developer could see how switching between endpoints changes the includes and also look at the resulting admin.js
and admin.css
files. The live demo would be at http://examples.totaljs.com/blocks/
.
To implement live previews I assume it would require the routes in each example to be unique, or maybe there is some other way? If you think such an approach would be useful, let me know what sort of changes are required and I'll start tweaking the examples to facilitate running them side by side on the same node server.
We'd probably need some way to tweak the examples when running on the demo server - for example, you wouldn't want loads of emails from the controller-mail
example, so we'd need some way to prevent it sending mails when running on demo server. Perhaps running the demo site in 'debug' mode would facilitate functionality switching?
Hi, @petersirka
I got an error message WebSocket connection to 'ws://127.0.0.1:8000/' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
in chrome broswer when I test custom protocol socket
F.websocket('/', socket_private_homepage, ['json'], ['privatechat'], ['*']);
and it's also has the same problem in Opera
, IE11
, Microsoft Edge
, safari
expect for firefox
.
I found the cause of the trouble by RFC6455 and do patch as follow:
line: 12960 in total.js/index.js
var SOCKET_RESPONSE = 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nX-Powered-By: {0}\r\nSec-WebSocket-Accept: {1}\r\n\r\n';
fix to:
var SOCKET_RESPONSE = 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nX-Powered-By: {0}\r\nSec-WebSocket-Accept: {1}\r\nSec-WebSocket-Protocol: {2}\r\n\r\n';
line: 13650 in total.js/index.js
self.socket.write(new Buffer(SOCKET_RESPONSE.format('total.js v' + version, self._request_accept_key(self.req)), 'binary'));
fix to:
self.socket.write(new Buffer(SOCKET_RESPONSE.format('total.js v' + version, self._request_accept_key(self.req),protocols), 'binary'));
and now all browser is working well.
Example with passport.js is not working
TypeError: next is not a function
at Strategy.strategy.error (C:\Users\pc-dev\Documents\node_modules\passport\lib\middleware\authenticate.js:343:9)
at C:\Users\pc-dev\Documents\node_modules\passport-oauth1\lib\strategy.js:244:30
at C:\Users\pc-dev\Documents\node_modules\oauth\lib\oauth.js:543:17
at passBackControl (C:\Users\pc-dev\Documents\node_modules\oauth\lib\oauth.js:397:13)
at IncomingMessage.<anonymous> (C:\Users\pc-dev\Documents\node_modules\oauth\lib\oauth.js:409:9)
at emitNone (events.js:110:20)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1045:12)
at _combinedTickCallback (internal/process/next_tick.js:102:11)
at process._tickCallback (internal/process/next_tick.js:161:9)
======= 2017-06-23 15:28:18: TypeError: next is not a function TypeError: next is not a function
at Strategy.strategy.error (C:\Users\pc-dev\Documents\node_modules\passport\lib\middleware\authenticate.js:343:9)
at C:\Users\pc-dev\Documents\node_modules\passport-oauth1\lib\strategy.js:244:30
at C:\Users\pc-dev\Documents\node_modules\oauth\lib\oauth.js:543:17
at passBackControl (C:\Users\pc-dev\Documents\node_modules\oauth\lib\oauth.js:397:13)
at IncomingMessage.<anonymous> (C:\Users\pc-dev\Documents\node_modules\oauth\lib\oauth.js:409:9)
at emitNone (events.js:110:20)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1045:12)
at _combinedTickCallback (internal/process/next_tick.js:102:11)
at process._tickCallback (internal/process/next_tick.js:161:9)
Is it linked with this ?
IMPORTANT: Twitter doesn't return (after you logged) a PORT number (127.0.0.1/login/callback/... you must rewrite to -> 127.0.0.1:8000/login/callback/...)
Hi,
Can someone provide example with ionic framework.
Thank you.
Hello.
I send plain in controller with headers:
self.plain('* {color: red;}', 'Content-type: text/css');
but my response headers in browser:
Content-Type:text/plain; charset=utf-8
Hi, I am running my java application under localhost:8080, where in I GET request via ajax, whereas to total.js server running under localhost:8000
$.ajax({
type:"GET",data:'lid='+gprofile.lid,crossDomain:true,dataType:"jsonp",
url:"http://localhost:8000/getmyname",
success:function(data){
console.log(data);
}
});//ajax
And the console throws error as below
GET http://localhost:8000/getmyname?callback=jQuery21309127184972167015_1435457894103&lid=5584b74914b7fe30217c8321&_=1435457894104
controller.js is set as
framework.route('/getmyname',getmyname,['post']);
Please advise how to set my server to access cross-domain access or any other,
nosql.js line 2340
var stream = Fs.createWriteStream(framework_utils.join(self.directory, id + EXTENSION_BINARY));
should be
var stream = Fs.createWriteStream(framework_utils.join(self.directory, self.db.name + '#' + id + EXTENSION_BINARY));
Hi,
We wanted to know how to use FrameworkView methods in templates loaded by angularjs??
Is it possible??
Thanks
Hi, I use the example session cluster redis, when I run the app in the console appear this:
** OBSOLETE module.session: exports.install = function(framework <-- REMOVE ARGUMENT, options, name) { ...
** ReferenceError: delegate_request is not defined ReferenceError: delegate_request is not defined
How to solve this problem?
CHANGELOG: we have replaced [replyTo] argument for [language] argument.
Why?
I am trying to create a web application to receive xhr with json.
I wrote following code. but it did not work.
framework.route('/xhr/json/', json_example, ['xhr', 'json']);
Could anyone know how can I receive xhr with json?
Hi author, i think this can be perfect, but i dont know how to do now.
You could have simple example about Apollo server with totaljs ?
Hi peter,
I wanted a little more clarity on how to implement roles for authorization. Do you have any other examples i could go through.
authorization.js
F.on('module#auth', function(type, name) {
var auth = MODULE('auth');
// "id" from auth.login()
auth.onAuthorize = function(id, callback, flags) {
DATABASE(function(err, connection){
if(err != null) {
console.log(err);
return;
}
connection.query('USE system_curry', function(err, rows) {
if (err != null) {
console.log(err);
return;
}
connection.query('SELECT * from users', function(err, rows) {
connection.release();
if (err != null) {
console.log(err);
return;
}
for(var i = 0; i < rows.length; i++){
if(rows[i].token === null ){
callback(null);
return;
}else if(rows[i].token == id){
callback(rows[i]);
}
}
});
});
});
};
});
controller/default.js:
The way i login
auth.login(self, rows[i].token, rows[i]);
Hi,
This is the common challenge, but looking for your advise. I have a web application which is running under total.js where my database lives. I have my mobile app which is read/delete/modify my total.js web server using AJAX call. (The same can be done using web application itself, where I manage all session variable.)
I do not want the mobile app user to sign-in all the time but at the first time. At the first login, I store the user ID in the localstorage and rest of the AJAX accesses I use localstorage details as credentials. In this case I will not have session variable. How I can restrict the total.js application such total.js will response only for my mobile app HTTP GET request, not by others.
How do I wrap this in a controller callback to send the returned data to the view:
self.$get(self, self.callback())
function view_stuff () {
When this (self.$get(self, self.callback())) is done, fire callback and send data to view ...
}
This self.callback() is confusing the shit out of me ...
Hii,
can you create an example of angular 4 with typescript that use server side render?
Thanks,
Khurram
Hi Peter,
I want to use socket.io in my app, I found an example :
https://github.com/maxprog/total.js-socket.io
in this example socket was defined in debug.js like this :
require('total.js')
var socketio = require('socket.io');
F.on("load", function()
{
this.io = socketio.listen(this.server);
this.io.on('connection',function(socket){
console.log('New connection');
socket.on('message',function(data){
console.log(data);
socket.broadcast.emit('receive',data.message);
});
});
});
F.http('debug');
But I need to definesocket.emit(...)
on my controller after one of my api has called.
How can I do that?
Hi, I used the example live-streaming-upload, I've followed the instruction, I ran 2 terminals, one to run node index.js and another upload.client.js but I'm ended up with this:
Mac-mini-de-Ivan:live-streaming-upload Ivan$ node upload-client.js [ '/Users/Ivan/Desktop/e/abstract_pyramids-1920x1080.jpg', '/Users/Ivan/Desktop/e/alamanos_beach-1920x1080.jpg', '/Users/Ivan/Desktop/e/autumn_sunlight-1920x1080.jpg', '/Users/Ivan/Desktop/e/bananaman-1920x1080.jpg' ] –----> /Users/Ivan/Desktop/e/abstract_pyramids-1920x1080.jpg ERROR { [Error: socket hang up] code: 'ECONNRESET' } Error: socket hang up at createHangUpError (_http_client.js:215:15) at Socket.socketOnEnd (_http_client.js:293:23) at Socket.emit (events.js:129:20) at _stream_readable.js:908:16 at process._tickCallback (node.js:355:11)
I don't know what means socket hang up.
Would you mind how to solve this problem?
hi,
do you have modules to detect crawler bot from google or another engines?
@ckpiggy please help !
The example link in "examples/csrf/readme.md" is death.
Hi,
i play around with some tests and i struggle with error handling in this example. I wrap all asserts in try catch blocks to get a better error handling. Without try catch my tests run into an endless loop with no response.
exports.run = function() {
try{
F.assert('controller.increment()', function(next, name) {
testerror
assert.ok(F.controller('default').functions.increment(1) === 2, name);
next();
});
catch(e){console.error(e);}
};
total.js is great.
Can you please create a meteor walkthrough kind of tutorials (https://www.meteor.com/tutorials). Currently, one confusion I am facing is that how to structure the codebase and what code part will go into which section, say I am writing a functionality , does it go to module or definition or packages .
Thanks
Hey Peter,
How can I fill the mail content?
(There's no doc about the arguments about the mail() function. You took the example with a redirection on a .html page.)
Thanks.
I've just tried mail example and it failed.
Google says that the app that is trying to connect is "less secure" and the only way around is to allow "Access for less secure apps" which i have currently disabled.
https://www.google.com/settings/security/lesssecureapps
More info: https://support.google.com/mail/answer/78754
I'm running my app on localhost
[Error: 534 5.7.14 HTTPS://SUPPORT.GOOGLE.COM/MAIL/ANSWER/78754 FU5SM404200WIC.0 - GSMTP]
======= 2015-09-15 20:25:38: Error: 534 5.7.14 HTTPS://SUPPORT.GOOGLE.COM/MAIL/ANSWER/78754 FU5SM404200WIC.0 - GSMTP Error: 534 5.7.14 HTTPS://SUPPORT.GOOGLE.COM/MAIL/ANSWER/78754 FU5SM404200WIC.0 - GSMTP
at TLSSocket. (D:\blabla\api\node_modules\total.js\mail.js:685:11)
at TLSSocket.emit (events.js:107:17)
at TLSSocket. (D:\blabla\api\node_modules\total.js\mail.js:566:12)
at TLSSocket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at TLSSocket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:538:20)
Is there something wrong on my end or can i do something to make the app "more secure"?
Thanks for any help
The auth module suggests using !role
whereas the authorization-roles example uses @role
. Is there a difference?
sorry about this question, i'm new in total.js.
But i find in examples and nothing like that.
please help ?
ps: good if we have super simple demo code about model, controller, view on README or website
Fresh install of example, server throw internal error 500 and terminal says:
query -> all
user ---> TypeError: Cannot call method 'find' of null ([object Object]) TypeError: Cannot call method 'find' of null
at Object.json_user_query (/home/u/projects/total/controllers/user.js:19:7)
at Subscribe.doExecute (/home/u/projects/total/node_modules/total.js/index.js:4:3745)
at Subscribe.execute (/home/u/projects/total/node_modules/total.js/index.js:4:2473)
at Subscribe.prepare (/home/u/projects/total/node_modules/total.js/index.js:4:3435)
at Subscribe.doEnd (/home/u/projects/total/node_modules/total.js/index.js:4:5342)
at IncomingMessage. (/home/u/projects/total/node_modules/total.js/index.js:4:1332)
at IncomingMessage.emit (events.js:92:17)
at _stream_readable.js:929:16
at process._tickCallback (node.js:419:13)
Any advice?
Thanks in advance.
I have a ubuntu vm running under windows which is running the totaljs example. But i cant access them on localhost:8000 from my host machine.
If i have a minimal example with just a node server running on 8000 everything works fine. So firewall/proxy should not be a problem.
Also if i run totaljs locally on windows it works fine.
Do i need any settings to run totaljs in a vm?
As stated in the definition for a problem:
// throw a custom problem
if (self.user === null)
self.problem('User is offline.');
self.plain('homepage');
});
or
framework.route('/forbidden/', function () {
var self = this;
self.view403('A visitor was denied.');
// IMPORTANT:
// self.view500(error)
});
I propose a rename.
Please add comments that describe the flow of what is going on, as it is unclear to new comers what is actually going on here.
examples/authorization/controllers/default.js
Hi peter,
I wanted to change one item in my action (changingItem
in my query) which should be get
route, from my post action method . In another word I need my couchQuery
api gave me different array after each time I post Item
to my couchQueryPost
api and I call it .How can I do that?
exports.install = function () {
F.route('/couchQuery/', json_query, ['cors']);
F.route('/couchQueryPost/', json_search, ['post']);
};
function json_query() {
var self = this;
console.log("inside");
var query = N1qlQuery.fromString("SELECT Title FROM `inform` WHERE (`docType`='" + `changingItem `+ "')");
myBucket.query(query, function(err, res) {
if (err) {
console.log('query failed', err);
return;
}
self.json(res, true);
});
}
function json_search() {
var self = this;
// Do somthing here
// for example ----> changingItem = self.body.item
}
Hello,
I would like to report, that examples with angular are not working.
I figured out, that I have to add config-release file, which has to contain key directory-angular set to /app/ and in index.js set variable debug to false.
$timeout(function() {
_ws.send(encodeURIComponent(JSON.stringify({ type: 'change', message: _username })));
}, 500);
replace to the below:=========
_ws.onopen = function () {
_ws.send(encodeURIComponent(JSON.stringify({ type: 'change', message: _username })));
};
does not work properly.
path '/_next/.../' route is not directed
When I'm trying to use your validation example. I run it normally and if I submit I always get "Form is valid".
When I checked validation. I found error in client-side javascript in view index.html.
I fix it with this.
$(document).ready(function() {
$('button').bind('click', function() {
$.post('/?ts=' + new Date().getTime(), $('#f').serialize(), function(d) {
var err = $('#error');
d = JSON.parse(d);
if (d instanceof Array) {
err.empty();
d.forEach(function(o) {
err.append('<div>' + o.error + '</div>');
});
err.show();
return;
};
err.hide();
alert('Form is valid.');
});
});
});
======= 2015-05-02 18:00:29: framework.install('model', 'users') ---> SyntaxError: /Users/polemarch/Desktop/project/nodejs/examples/0-learn/models/users.js:22
User.setGet(function_(error, model, options, callback) {
^
Unexpected token * /Users/polemarch/Desktop/project/nodejs/examples/0-learn/models/users.js:22
User.setGet(function_(error, model, options, callback) {
^
SyntaxError: Unexpected token *
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at EventEmitter.Framework.install (/Users/polemarch/Desktop/project/nodejs/examples/0-learn/node_modules/total.js/index.js:1:29139)
at /Users/polemarch/Desktop/project/nodejs/examples/0-learn/node_modules/total.js/index.js:1:24484
at Array.forEach (native)
I like Total.js, but ended not yet fully understand the operation of the "Schema" for example the difference between $save and $workflow. I have already read the documentation :)
If there is any example (CRUD) would be great.
Thank you very much.
I am trying to create a web application websocket like example
but not working with ie 11
If I create a section like this: @{section("scriptsFooter")}
using double quotes, the view can't find the section.
Thank you for this great framework.
This example seems somewhat pointless...
https://github.com/totaljs/examples/tree/master/authorization-www-basic
In particular, what is self.baa
supposed to be?
Would it be best to just remove this example and instead have people go to the main 'auth' module?
Alternatively, the example could be refactored to show how to route depending on 'authrorized'
vs 'unauthorized'
, thus providing a very basic example of how F.onAuthorize
delegate and associated flags work?
Hi,
I tried total.js few days ago and I am working on the emptyproject-restservice-master repository for testing purpose.
Based on your example I managed to update the model, the controller for my needs.
In the model user.js, I try to upsert a record into the nosql database
users.upsert(data).make(function(builder) {
builder.where('key', data.key);
builder.callback(SUCCESS(callback));
});
This is the test I made to test your rest API. Post and Put request use the same function in the controller.
it's working when the record does not exist but the upgrade does not do the job.
bbb user is never upgrade with ccc values.
it("Ajout d'un utilisateur", function(done) {
var json = {
key: 'user1',
firstname:'aaa',
lastname:'aaa',
email:'[email protected]',
phone:'+421903163302'
};
request.post({
url: 'http://127.0.0.1:8000/api/users/',
json: json
}, function(err, res, body){
expect(res.statusCode).to.equal(200);
//expect(res.body.success).to.equal(true);
console.log(res.body);
done();
});
});
it("Ajout d'un 2ème utilisateur", function(done) {
var json = {
key: 'user2',
firstname:'bbb',
lastname:'bbb',
email:'[email protected]',
phone:'+421903163302'
};
request.post({
url: 'http://127.0.0.1:8000/api/users/',
json: json
}, function(err, res, body){
expect(res.statusCode).to.equal(200);
expect(res.body.success).to.equal(true);
console.log(res.body);
done();
});
});
it("Modification du 2ème utilisateur", function(done) {
var json = {
key: 'user2',
firstname:'ccc',
lastname:'ccc',
email:'[email protected]',
phone:'+421903163302'
};
request.put({
url: 'http://127.0.0.1:8000/api/users/user2/',
json: json
}, function(err, res, body){
expect(res.statusCode).to.equal(200);
expect(res.body.success).to.equal(true);
console.log(res.body);
done();
});
});
Any ideas ?
Cheers.
do you think we can have angular-websocket as dependency for the WebSocket example
hi, I have domain with .ac.id in the end
instead of null self.subdomain return my domain name..
how to get right subdomain and domain name?
When I cd into an example directory and type node index.js, I get:
Error: Cannot find module 'total.js/debug'
Example:
Directory: example/workers
Running: node index.js
Result:
Error: Cannot find module 'total.js/debug'
Where do I get the debug from?
Hi Peter,
I am working with SchemaBuilder , I looked it (http://docs.totaljs.com/v1.7.x/en.html#api~Builders.SchemaBuilder. and https://github.com/totaljs/examples/tree/master/framework-schema-and-validation)
but not understand some methods (rule,transform, workflow,compose)
Maybe you can create a new example with use all methods.
Thanks,
I need to work with Swagger to document my APIs . Is there any way to do so?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.