Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emberjs: Use Websocket backend as data source

I am fairly new to ember.js and client side development in general. My current setup looks sth like this:

Client/Server Schema

This is NOT using a library like socket.io or so. (Protocol example below)

So in general, this is what i want to achieve. I have already written an Object which will return a Promise on requests. Since i need the login step in the beginning I wanted to create the object somewhere, and on creating, log in automatically.

Now my questions:

  • Where to define the Class in the ember framework?
  • Where to create/store the object after creation (needs to be singleton since the login is only valid while the socket is open)?
  • How to access the Object, when i need to send requests.

Sample Login request:

Request:

{
    "type": "request",
    "subtype": "apilogin",
    "id": 1234,
    "data": {
        "username": "<string|null>",
        "password": "<string|null>",
        "token": "<string|null>"
    }
}

Answer:

{
    "type": "answer",
    "subtype": "apilogin",
    "id": 1234,
    "error": 0,
    "errormessage": "",
    "data": {
        "token": "<string>"
    }
}

The token is just another way to login which is valid up to 15 minutes after the socket closes. (To reconnect after network errors or similar).

Since i have never really done something like this I'm kinda having problems as where to put stuff in the framework and how to access them.

like image 620
belst Avatar asked Sep 22 '26 01:09

belst


1 Answers

I think this scenario is a perfect candidate for Ember services. To answer your questions separately:

Where to define the Class in the ember framework?

Anywhere is fine. If you're using Ember CLI you probably want to put it in the services directory.

Where to create/store the object after creation (needs to be singleton since the login is only valid while the socket is open)?

The Ember container will create the instance for you. By default, all items looked up from the container are singletons, so you shouldn't have to worry about this.

How to access the Object, when i need to send requests.

You should inject the service into the classes you need. To take from the guide I linked to, this will inject the service into a single class:

Ember.Component.extend({
    // Make sure you name your object SocketService
    socket: Ember.inject.service()
});

Or, to inject it into all classes of a type (for instance, to inject it into all routes), use an initializer:

application.inject('route', 'socket', 'service:socket');
like image 152
GJK Avatar answered Sep 25 '26 05:09

GJK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!