Help making tutorial apps

Thanks for the link. I’ll read through this but goddess I think this is going to require coffeee. Okay so HTTP is the signal so how do I now use HTTP with javascript and json correctly and get it all passed and coded? Okay going to brew some coffee and read this.

@Blindsite2k the “how do I http” question depends on your chosen runtime + libraries.

For node you got the examples already in the documentation.
If you’re doing client side / browser based work then you either use raw XHR or usually cleaner and more portable use whatever http abstraction your framework of choice comes bundled with there’s a jQuery tutorial or maybe Angular?

it’s really no more complicated than that.

1 Like

Oh lord I haven’t really gotten into jQuery or Angular. Okay MOAR reading.

Adding to that, JavaScript is especially fun in this regard: other languages (say, C++) have special constructs that represent methods/member functions so that it only makes sense to invoke them on particular objects. In JavaScript “member” functions are actually just normal functions that happen to be invoked as members of objects. So, in JavaScript this is a special identifier within a function body whose meaning depends on the “context” of the function call, so it is the object that the function is a member of if it’s invoked as a member of an object, undefined or the global window object or something like that if the function is called “loose,” or a custom object if the function is invoked indirectly via .call or .bind (because JavaScript functions are also objects and have their own methods). For instance, here’s some code and what I get as output when I run it in my browser:

class Type {
  member() {
    console.log(this);
  }
}
function free() {
  console.log(this);
}
let obj = new Type();
obj.member(); //< obj
free(); //< the global Window object
obj.member_free = free;
let free_member = obj.member;
obj.member_free(); //< obj
free_member(); //< undefined
free.call(2); //< Number object with value 2 (not just 2, because this has to be an object)

All of the details of how this works are better explained by the MDN page on it.

The upshot of all of this stuff about how JavaScript handles this is that this takes on a new value for each function invocation, whether it completely makes sense or not, and this makes programming with closures interesting. In C++, when you define an anonymous function inside of a member function, you can just capture this and it will refer to the same object as in the member function (though that object might no longer exist when the lambda is called if the code was written incorrectly, which is what makes capturing by reference/pointers in C++ exciting). JavaScript, on the other hand, will come up with a new value for this when the anonymous function is called according to the same rules sketched above, so even though it would intuitively look like it ought to capture the this value from the enclosing function, it doesn’t. Doing var self = this is a way of getting around this problem, because self is captured normally by the enclosed function and so it doesn’t have the problem of referring to the wrong thing when that function is called like this does.

Also, the new version of JavaScript (ES6) has a new way of specifying lambdas called “arrow functions” which are much more succinct than normal JavaScript function declarations but which also have the nice property of automatically capturing this like one would expect them to in this case. I’m not sure what level of ES6 support one can expect for browsers running SAFEsites, but if it is supported these are clearly a much less confusing way of handling creating anonymous functions inside of member functions.

2 Likes

Uh okay about 3/4s of that went right over my head sorry. Also I’m not sure the code you’ve written is javascript. I mean it kind of looks like it but it’s weird. Looks more like node.js but maybe I’m just ignorant or something.

Nope, it’s just also ES6 (or the class part anyway, since that’s another useful syntax they’ve added to abstract over the weird prototypal inheritance scheme that JavaScript uses; the rest should still be valid old-style JavaScript). Besides that, though, programmers make fun of JavaScript a lot because of all of its strange quirks, and things like this are part of what give it that reputation; if it doesn’t make much sense to you at first, you’re not alone since it doesn’t make much sense in general. But JavaScript is the official language of web browsers, so it’s what web code has to be written in (disregarding things like Emscripten which compile code from other languages to JavaScript, as absurd as that is).

1 Like

I think you just described why javascript is a marmite language! :slight_smile:

1 Like

    As near as I can figure this is your phone cord <=> http://localhost:8100/auth

@blindsite2k taking this from where we left this at, let us be very practical, your switchboard-phrase:

http://localhost:8100/auth

Typing that in my browser gives me:

{"errorCode":400,"description":"Unauthorised"}

Magical Mystery Tour?

No, I thought I knew something and started the Safe Launcher before pointing my browser to that address.

Don’t know about you but things are looking up already, “squiggly brackets” or “curly brackets”, signifying life in the hereafter in the form of a textual message from my own computer!

Dare I say it, must be the ‘JSON’ they were pointing us to.

So it’s true, tickle it and it grins back, an ant is lurking somewhere on our motherboards …

Your other questions have I think been answered. This is set by the application which uses RemoteStorage.JS code - hence not in the repo sorry (although I think it is documented in the comments). Here’s an example use:

    // SAFE Network backend requires application identity and required permissions rather than
    // API keys (authentication is handled by the user via SAFE Launcher, not a server)
    remoteStorage.setApiKeys('safestore', 
        {    
            // For details see SAFE Launcher /auth JSON API
            app: {
                name: 'RemoteStorage Demo',        // Your app name etc.
                version: '0.0.1',
                vendor: 'remoteStorage',
                id: 'org.remotestorage.rsdemo'    // Identifies stored data (unique per vendor)
            },
            permissions: ['SAFE_DRIVE_ACCESS']  // List of permissions to request. On authorisation, 
                                                // holds permissions granted by user
        }

As you can see it is pretty much what is asked for by /auth in the SAFE API.

3 Likes

Yeah I’ve been reading up on ajax and the xhttp functions. I think one could use that to send the information over http to the api. What I’m wondering is how to correctly send and receive. I haven’t done a lot of work using http before, using javascript or otherwise, so a lot of this is new to me.

Also I’m wondering even if one gets the data how does one say input it into a database properly. Questions questions.

    … to send the information over http to the api.

Had s sneak peek, this is from the Safe Network API docs, if you want something done, how to send it off, with specified parameters. Not longwinded at any rate:

request.post(endPoint, {  
  json: true,
  body: payload
}, onResponse);

Stay tuned, more later. Maybe we have a time zone between us?

yes but remember that’s written in node.js and while node is derived from javascript I’m not sure how much is still valid in regular javascript.

Yes we probably o have a timezone between us. I’m on Pacific Time, GMT -8, if that helps.

    node.js <=> regular javascript

So what to use, Node or regular JS to approach the Safe API? I had a chance to try the two “auth”-examples in the API-documentation under Node just now.

More or less cut-and-pasted the first one and the Launcher started to balk already, for me to authorize a newcomer to the scene. Take returned token from the ‘console’ to the other MaidSafe code-fragment and this checked ‘OK’ for “still authorized”.

Coaxing Node into cooperating was the real hurdle. It already sat on my Windows-machine, installed by another application, otherwise there is this download of a single Node.exe as an alternative to a full installation.

If you opt for the single executable you do have to find out how to install other extras yourself but one can have Node married to this wonderful companion, NPM, which then will do all the shopping for you afterwards.

NPM assisted for example when Node wanted ‘request’ to be present to execute the Safe API code to delegate an HTTP-POST and -GET.

About the latter, you had an earlier question answered in the forum I noticed today?

And it is what they say it is, that much less JavaScript to accomplish what you want is a compelling reason to invest in what do IT-books call it, “Mastering this or that”, in this instance Node.

So where are we?

– Our intention to collaborate together pays of nicely - at least for me for now ;o)

– You probably still wish us to explore the pure JavaScript-way of doing things which is OK by me

– Because I will counter with a Windows-scripting initiative which is different from JS

– We’ll have to keep an eye on this other part of the forum where they discuss the future of the Launcher as to not have the rug pulled from under us

– We have to compare notes in regard to what we use for OS and how you want to proceed, was yours in fact an API-question or a general learning-more-of-programming-question?

I’m looking into using ajax and the xhttp functions there but I’m not sure exactly how to send and receive the json information that is supposedly sent back to the user over http. ajax seems to only have a function to receive text or xml so I’m not quite sure how to handle that or corretly convert it into a json file.

My code shows how to do this, example:

var response = JSON.parse(xhr.responseText);
    
          // Save session info
          self.configure({ 
              token:                response.token,        // Auth token
              permissions:          response.permissions,  // List of permissions approved by the user
            });
1 Like

    using ajax and the xhttp functions

What about forgetting JSON for a moment and start with going into the air trying to reach the Safe Launcher (loaded and authorized)?

Did where you was give you example code for using this ‘XMLHttpRequest’ with JS? If not, in your case you just want a minimal HTML-page which harbors the Javascript for sending and receiving.

For instance “Step 3 – A Simple Example” here at developer.mozilla.org probably will do it.

The guiding principle of this REST-thing @dirvine pointed us to: whatever you want to ask from the Launcher is immediately obvious because of the endpoint selected by you, no need for an additional specification of your intentions.

Why the earlier browser experiment for ‘/auth’ did work.

And that’s why we can simply repeat the experiment this time coming from a bit of Javascript, we’re not going to give the Launcher anything but just the absolute bare minimum of a call (HTTP GET Request) and see if it reacts to it.

To do this we have to copy the code and surround it with code for an HTML-skeleton page:

<!DOCTYPE html>
<html>
<body>

   Step 3 - Example code from the link above goes here

</body>
</html>

One change to that example is necessary, where the code should go once set in motion, so here the original:

makeRequest('test.html');

Is adapted to address the Launcher on our PC like so:

makeRequest('http://localhost:8100/auth');

So what do you say, yes? And if you also did copy that specific example does it look like what I have?

1 Like

You need JSON as its part of the API and part of how the API sends the token information back to you.

This is horrible grammar to the point I’m not understanding what you’re saying. Also on SAFE inline scripts are disabled.

Do you mind explaining what exactly your code does? What exactly does var response = JSON.parse(xhr.responseText); do? More specifically xhr.responseText ? Does one prepare code assuming they know what the response will be?

I am having the same kind of trouble/confusion with the API stuff @Blindsite2k.

What I would love to see is a HTML/CSS/JS example of a simple launcher authorization for a “Hello World” type setup. I believe codepen even will allow interactive embedded pens on discourse…maybe that is something that can be part of the dev forum too in a bit!

1 Like

Time out …

It will use JSON, trust me - if we keep it up, this week ;o)

The Mozilla sample or what, my description of what it does?

But how about its purpose? This is not THE app, it’s a few simple steps aimed at getting the bulb switched on. As it were.

Will happily use anything else you provide, because at this stage we should try to get something working, not do everything by the book. Would this ever morph into a real tutorial then there is ample opportunity to get everything else right?

As you know that could easily be remedied later on in any code you write later:

 <script src="./scripts.js"></script>

Then again, this is a simple experiment, us trying to access the Safe Network programmatically for the first time, nothing else.

How do you see it double back later from the other end on the Safe network?

True, there are concerns about accessing the Safe Launcher from outside the PC it sits on but at this stage you should not worry too much, this thread is titled “Help making tutorial apps development”.

So, show me yours :sunglasses:

Guys can we move this thread to the new Dev Forum?

It seems like a perfect fit, as it would be incredibly useful to new devs looking on there

EDIT: just made a thread myself. Join & discuss!