Coder Social home page Coder Social logo

ember-data-sails's Introduction

ember-data-sails

Adapters and tools for Ember to work well with Sails. Provides SailsSocketService, SailsRESTAdapter, SailsSocketAdapter, SailsSerializer and extends the store so that you can subscribe for records while pushing a payload.

Note: If you want to use this adapter with a version of SailsJS < 0.11.0 you have to use version 0.0.12 of this addon.

  • SailsSocketService: injected in adapters, controllers and routes on sailsSocket property, it allow you to do Ember friendly requests using Sails socket. Example:

    // in app/controllers/application.js
    this.sailsSocket.request('get', '/someController/someAction', {name: 'Huafu'}})
      .then(function(response) {
        // do something with the response
      });

    It'll use by default the sails.io.js located at <hostname>:1337/js/dependencies/sails.io.js, but you can change this using configuration in config/environment.js file:

    ENV.APP = {
      // if you want some useful debug information related to sails
      SAILS_LOG_LEVEL: 'debug',
      emberDataSails:  {
        // default is to use same host and port as the ember app:
        host: '//localhost:1337',
        // this is the default and is the path to the sails io script:
        //scriptPath: '/js/dependencies/sails.io.js'
      }
    }

    Also don't forget to add the rules for CSP:

    // allow to fetch the script
    ENV.contentSecurityPolicy['script-src'] += ' http://localhost:1337';
    // allow the websocket to connect
    ENV.contentSecurityPolicy['connect-src'] += ' http://localhost:1337 ws://localhost:1337';
  • DS.SailsSocketAdapter: use this adapter when you want to use sockets for your model(s)

  • DS.SailsRESTAdapter: use this adapter when you want to use sockets for your model(s)

  • DS.SailsSerializer: used by default when you use a Sails adapter, you shouldn't need to access it but it's there in case

  • DS.Store.pushPayload([type], payload, [subscribe=false]): as the original one from Ember Data, except it accepts an additional parameter which, when set to true, will tell the socket adapter to subscribe to the pushed records (see below)

  • DS.Store.subscribe(type, ids): tells the sails socket adapter to subscribe to those models (see below)

Installation

  • npm install --save-dev ember-data-sails

CSRF config

  • If you want to use CSRF token with the REST adapter, don't forget that you'll need to setup it as an object (and not true only) in the SailsJS config file (thanks @tibotiber for figuring this out).

Using

You must set sails.config.blueprints.pluralize to true in your Sails API to make the adapters works

  • If you are using sane (package sane-cli), you must change the configuration in server/config/routes to allow /__getCookie (and /csrfToken if needed) to be handled by the SailsJS core:

    --- a/server/config/routes.js
    +++ b/server/config/routes.js
    @@ -50,7 +50,7 @@ module.exports.routes = {
       //This automatically serves all routes, apart from /api/** routes to ember
       //(which will be initialized in assets/index.html). This route needs to be
       //at the very bottom if you want to server other routes through Sails, because they are matched in order
    -  '/*': { controller: 'App', action: 'serve', skipAssets: true, skipRegex: /^\/api\/.*$/ }
    +  '/*': { controller: 'App', action: 'serve', skipAssets: true, skipRegex: /^\/(api\/.*|__getcookie|csrfToken)$/ }
     
       //You could also just serve the index view directly if you want
       //'/*': { view: 'index', skipAssets: true, skipRegex: /^\/api\/.*$/ }
  • The SailsSocketService is injected on all adapters, controllers and routes on the sailsSocket property

  • To use the SailsSocketAdapter as the default adapter, or as a model specific adapter, extend it from SailsSocketAdapter:

    // file: app/adapters/application.js
    import SailsSocketAdapter from 'ember-data-sails/adapters/sails-socket';
    
    export default SailsSocketAdapter.extend({
      /**
       * Whether to use CSRF tokens or not
       */
      useCSRF:              true,
      /**
       * The path to use when the CSRF token needs to be retrieved
       * Default is `/csrfToken`, if not heading `/` it'll be relative to `namespace`
       */
      //csrfTokenPath: 'some/custom/path',
      /**
       * Whether to group multiple find by ID with one request with a `where`
       */
      coalesceFindRequests: true,
      /**
       * The namespace of your API
       */
      namespace:            'api/v1'
    });
  • To use the SailsRESTAdapter as the default adapter, or as a model specific adapter, extend it from SailsRESTAdapter:

    // file: app/adapters/application.js
    import SailsRESTAdapter from 'ember-data-sails/adapters/sails-rest';
    
    export default SailsRESTAdapter.extend({
      /**
       * The host of your API
       */
      host:                 'http://localhost:1337',
      /**
       * The namespace of your API
       */
      namespace:            'api/v1',
      /**
       * Whether to use CSRF tokens or not
       */
      useCSRF:              true,
      /**
       * Whether to group multiple find by ID with one request with a `where`
       */
      coalesceFindRequests: true
    });
  • Since 0.0.11 you can ask the API to subscribe to some models, useful when you want for example to preload some data at the application start from some serialized JSON in a <meta> tag. While it's easy to push data into the store with store.pushPayload, then the records are not subscribed until you save them or get them again from Sails using the socket adapter. To push a payload and automatically subscribe to the pushed records, you can give an additional parameter to pushPayload method of the store which if true will automatically subscribe the models and records it can. This will use subscribeMethod, and subscribePath properties of the adapter to do a request on the API.

    • subscribeMethod: get, post, ... defaults to post

    • subscribeEndpoint: the endpoint to do the request on, defaults to /socket/subscribe

    • Of course you'll need to create a basic controller in your Sails API. Here is an example:

      // api/controllers/SocketController.js
      module.exports = {
        subscribe: function (req, res, next) {
          var ids, data = req.allParams(), model, subscribed = {};
          for (var name in data) {
            if (data.hasOwnProperty(name)) {
              model = sails.models[name];
              if (model) {
                ids = data[name];
                model.subscribe(req, ids);
              }
              else {
                sails.logger.warn('trying to subscribe to unknown model: ' + name);
              }
            }
          }
          res.json({});
        }
      };
  • Using sails-generate-ember-blueprints: if you want to use this adapter in conjunction with Ember blueprints for Sails from Marcus, you need to define it in the config/environment.js like this:

    ENV.APP.emberDataSails.useSailsEmberBlueprints = true;

TODO

  • Write more unit tests!!!
  • Auto re-subscribe to subscribed records/models after a connection reset (it's already automatically re-listening for the events on the socket, but if Sails application have rebooted, we need to re-subscribe on the server somehow with the client socket)

Authors

While this was first inspired from ember-data-sails-adapter, it has now been fully re-written, with a totally different approach, and, as of the day this was written, with more features.

ember-data-sails's People

Contributors

chrisbenson avatar huafu avatar labmorales avatar systho avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

ember-data-sails's Issues

CSRF mismatch when sails restarted

Hi,

Is there an easy way for me to fix the issue where if I restart my sails server, then the Ember App reconnects the socket ok, however it does not refresh the CSRF token and so when i try and save a record I get an error Code 403 - CSRF mismatch from the sails server.

I tried inserting

this.set('csrfToken', false);

into line 380 of services/sails-socket.js but it did not seem to help me.. anyone else come across this issue before?

thanks.

Paul.

how to get socket to connect on anything other than port 4200?

Please help as I must be missing a config somewhere...

I have a sails server running on port 1337
I have my app running as ember serve on port 4200
when I load the app in a browser I get streams of connection requests in firebug of:

GET http://localhost:4200/socket.io/?__sails_io_sdk_version=0.11.0&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&EIO=3&transport=polling&t=1438000496354-2

if i do a view source of the browser i see:

<script type="text/javascript" id="eds-sails-io-script" src="//localhost:1337/js/dependencies/sails.io.js"></script>
<script type="text/javascript">io.sails.autoConnect = false; io.sails.emberDataSailsReady = true;</script>

my config/environment.js contains:

APP: {
  SAILS_LOG_LEVEL: 'debug',
  emberDataSails:  {
    host: '//localhost:1337',
    socketUrl: '//localhost:1337',
  }
}

versions are:
ember-cli : 1.13.5
sails: 0.11.0
ember-data-sail : 0.0.15

what do i need to do, to get the socket to connect to port 1337 instead of 4200? thanks.

Client connection to sails server

I'm prototyping with your adapter, thanks for your work on this.

I'm reaching for some help understanding your setup.

Setup:
I have the client served on :4200 (standard ember cli) and the sails serving on :1337 (standard sails config)

Symptom: no model data loads from a model set to use sails adapter via either REST or socket, probably due to a 404 thrown from sails.io.js:2 (the minified socket.io):

GET http://0.0.0.0:4200/socket.io/1/?__sails_io_sdk_version=0.10.0&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&t=1422943732164 404 (Not Found)

I presume this url comes from the sails socket config, where its specified under the 'resource' key '/socket.io'. So why the 404 ... I guess I'm missing something in the configuration?

PS: Output the socket object in sails.io.js:221 shows an object with two events however: socketConnected and onActualSocketConnect.

So I'm stumped why the 404 and why no data. Any tips would be appreciated.

CSRF not present in SailsSocketService

Hi @huafu,
I'm trying to use the socket service but I'm getting an issue due to csrf settings. My call is as follow:

this.sailsSocket.request('post', '/support/post', postData).then(function(response) {
    console.log(response);
}

and I get the following error (doesn't even reach console.log):

[ed-sails] triggering event `didConnect`

undefined ember.debug.js:28602
RSVP.onerrorDefault  ember.debug.js:28602
__exports__.default.trigger ember.debug.js:51120
Promise._onerror ember.debug.js:52132
publishRejection ember.debug.js:50363
(anonymous function) ember.debug.js:28563
Queue.invoke ember.debug.js:854
Queue.flush ember.debug.js:919
DeferredActionQueues.flush ember.debug.js:724
Backburner.end ember.debug.js:149
(anonymous function) ember.debug.js:552 

Now, if I manually fetch the csrf token with postman and add it to postData before making the request, everything works just fine.

My settings are as follow:

export default SailsSocketAdapter.extend({
    useCSRF: true,
    coalesceFindRequests: true
});

Is the socket service inheriting the config of the socket adapter? If not, is there any extra settings for the socket service?
Thanks :)

Sails socket and nginx proxy

I struggled with getting ember connected to a sails api being served through an nginx proxy for quite a while. I found a workaround, and this is probably a problem with nginx or just how I've configured it, but there might be something that can be done in ember-data-sails (or in sails) to make it more compatible with nginx.

The problem:
The ember app could socket connect to the sails api through nginx, but any requests it tried to send through the socket wouldn't reach the api. I tried logging a message in node_modules/sails/express/node_modules/connect/lib/proto.js at the start of the app.handle method, which was the earliest handler I could find in the sails/express request life cycle, but nothing was ever logged (unless I used http instead of sockets).
No error messages appeared in the browser console or network profiler

Environment:
Sails 0.11.0
Ember CLI 0.2.7
Ember Data Sails 0.0.15
nginx 1.9.2
nginx conf:

server {
    listen 80;
    root /api_root;
    index index.html;
    server_name api_domain;
    location / {
        proxy_pass http://localhost:1337;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_pass_request_headers on;
    }
}

Observations:

  1. When ENV.APP.emberDataSails.host is set to a domain name with no port or protocol, eg "//api.example.com", the problem is present
  2. When ENV.APP.emberDataSails.host is set to a domain name with a port, eg "//api.example.com:80", the problem goes away and everything works fine
  3. When ENV.APP.emberDataSails.host is configured to include the protocol, the problem also goes away.
  4. Taking nginx out of the equation makes the problem go away for the 1st case

Your Approach vs Blueprints

Hi,

Not a bug, but just a quick question regarding your approach versus overriding blueprints. Seems like this may be easier to maintain long-term rather than overriding blueprints. Can you provide any insight?

Best,
James

Authorization and query params

I'm building an app that uses https://github.com/sane/sane-auth for api authentication. Basically it sets a token which is then send with each request from ember as part of an authorization header.

As far as I know, sockets don't allow setting the request header from the client side.
So my first idea was, adding a query parameter to each socket request containing the token. This would be normally done setting io.sails.connect(this.get('socketUrl'), {query: "param=my-param"}); or via io.sails.query.
However, this does not add any query parameters.

This have given me some headache, as I'm not too familiar with sockets in general. Do you have any suggestions on how to add authorization to each request?

Errors from sails (validations) aren't handled properly

Hey.

I've also created a PR for that: #30 , but just in case:

under the ajaxError function you've checked the data.errors, but sails response is with data.error not errors, so it never entered that place and just throw a new Error(data) instead. Same happened in the processRequest function where you did use the isErrorObject function, but then checked again for that .errors property that doesn't exists.

Here is the response I for from the server:
image

As you can see, no errors property

I'm using sails 11.2 with sanestack if that matters.

Thanks,
Dan

Abandoned?

Hey Guys,

I was wondering if this project is abandoned, or if it is no longer maintained. There are five pull requests.

M

Sails socket publish not added to the store after upgrade from 0.0.13 to 0.0.17

Hi huafu,

I'm having and issue after my upgrade to ember 2.1, ember-data 2.1 and ember-data-sails 0.0.16/0.0.17. I'm using the SailsSocketAdapter and the ActiveModelSerializer. The sails backend has not changed (0.11.0). Any help is appreciated.

All standard requests are working as expected. Issues arise when a socket push message comes in. In my case for "comments".

When client A creates a comment, client B gets the websocket frame, but the comment is obviously not parsed as expected. With [email protected] and an old [email protected] the record was parsed and created, everything went fine (UI is updated, notification is created). In 0.0.16/0.0.17 with [email protected] not. Using the ember inspector I can see that the new model is not created.

Here the frame that comes from sails:

42["comment",{"verb":"created","data":{"comment":"test","idx_start":null,"idx_end":null,"selected_content":null,"anchor_id":"e8d51873-5732-4d3f-a91b-959dd483ba7c","page_id":22,"created_by":1,"id":80,"createdAt":"2015-10-28T09:33:10.000Z","updatedAt":"2015-10-28T09:33:10.000Z"},"id":80}]

In the receiving client I can see that the above frame is received. I can see that there are no errors on the console. I can see that there are no promises at all (i.e. no failing promises).

I've tried 0.0.13 - 0.0.15, but they won't work due to the ember-data changes from typeKey to modelName. 0.0.16 an 0.0.17 share the described behavior.

Am I missing something or might this be a bug?

Thanks, BR, toovy

Bind listeners on custom events

In sails I'm triggering or broadcasting custom websocket events using snipptes like this :

sails.sockets.broadcast(roomName, "myCustomEvent",
          {
            payloadProperty1: payloadValue1,
            payloadProperty2: payloadValue2,
          }
        );

Using your service I can try to listen on those events with the following snippet (this is coffeescript, I use it to differentiate my code from your code )

@sailsSocket.listenFor 'myCustomEvent'
@sailsSocket.on 'myCustomEvent.undefined', @myCallback

the reason for the '.undefined' is because you suppose the existence of a verb property in the message which I didn't put.

handleSocketMessage: function (event, message) {
      if (!isAlive(this)) {
        return;
      }
      this.trigger(event + '.' + message.verb, message);
    },

I could add a verb to my payload but I think it's not very natural since the sails doc doesn't talk about it ( http://sailsjs.org/#!/documentation/reference/websockets/sails.sockets/sails.sockets.broadcast.html ).

I think the better idea is for you to add the verb on your ember even only if it exists and would even suggest to go further and trigger a "global" ember event all the time without the verb and a second "focused" event with the verb if there is one. This would allow to bind either for a specific verb or fall all the possible sub events of an event.

I also find it a little bit weird to be forced to listenFor an event before being able to call on on the service. it would be easier if calling on (or another method name if you do not want to break your api ) would bind the listener and register the callback at the same time

No more generators

I don't think there is any more generators needed if you directly fetch the sails.io.js script from sails.

On the other hand you need to update your ember cli content security policy like this :

    // allow to fetch the script
    ENV.contentSecurityPolicy['script-src'] += ' http://localhost:1337';
    // allow the websocket to connect
    ENV.contentSecurityPolicy['connect-src'] += ' http://localhost:1337 ws://localhost:1337';

this.store.find with params

Basically this is the issue that I am experiencing:

If in model hook in my route I have return this.store.find('user'); everything is working fine (if new user is created I get notified and I see new user rendered on page).

On the other hand if I have return this.store.find('estate', { limit:3 }); I get notified ([ed-sails] triggering event user.created) that user is created and also if I check out ember inspector I can see new user in data tab but new user is not rendered on page.

Is this intentional or is there something else going on here?

Primary Key change

Hello,

I am trying to use the socketAdapter to get data in/out of a sails API server. I can get lists of my model (called 'requestType' ) ok, however when the system tries to grab a single record it seems to send params of

{ requestType_id: 6 }

but if this is passed to the store.query call then nothing gets returned. If however I change the params object to:

{ id: 6 }

then I get a single record returned ok.

My question is where is the best place to change this to get the two systems communicating, is it a serialiser, in the model call of each route or on the API?

documentation

Hi,

I have a very simple model (one attribute) just for test purposes and I can see the initial socket connection happening and on my sails console in silly log mode it registers all the subscriptions before sending back the data in the model. Ember receives the data fine, but if I create a new record in sails or update a record (via say postman direct to the API) nothing shows up in my ember client. Also I can see in sails log that it has published the event when I update a record.

I've gone over and over the documentation, but I can't really see how I should be registering to listen for events. I think there is mention somewhere of being able to observe the events. I'm likely wrong, but I kind of got the impression you just need to do a store.find and return your model and the socket adapter just listens from that, but that doesn't seem to be happening.

I've read through all of the issues open and closed to see if there are any code snippets that could shed some light. I think one mentions something about computed properties, I've tried things like .on('interaction.update') .on('interaction.create') .observes('interaction.update') etc, but nothing seems to make any difference.

I tried this.sailsSocket.listenFor('interaction.update', true); which showed up in the console as
[ed-sails] attached event interaction.update on socket

but still nothing when I update or create a record. So I'm just wondering is there something I'm missing in regards to enabling the listener?

Thanks in advance, any assistance is greatly appreciated.

Logs and details below

model interaction
export default DS.Model.extend({
name : DS.attr('string')
});

ember-data-sails log when route loads
[ed-sails] socket not connected, listening for connect event before giving it
ember.debug.js:258 [ed-sails] socket core object ready
ember.debug.js:258 [ed-sails] triggering event didInitialize
|> Now connected to Sails.
___/ For help, see: http://bit.ly/1DmTvgK
(using browser SDK @v0.11.0)

ember.debug.js:258 [ed-sails] triggering event didConnect
ember.debug.js:258 [ed-sails] socket GET request on /api/v1/interactions: SUCCESS
ember.debug.js:258 [ed-sails] โ†’ request: undefined
ember.debug.js:258 [ed-sails] โ† response: Object {interactions: Array[29]}

ember route loading calling model in sails
server | Fri, 04 Dec 2015 01:46:27 GMT: verbose: Receiving incoming message from Socket.io: { method: 'get',
server | Fri, 04 Dec 2015 01:46:27 GMT: verbose: Interpreting socket.io message as virtual request to "get /api/v1/interactions"...
server | Fri, 04 Dec 2015 01:46:27 GMT: silly: Handling virtual request :: Running virtual querystring parser...
server | Fri, 04 Dec 2015 01:46:27 GMT: silly: Handling virtual request :: Running virtual body parser...
server | Fri, 04 Dec 2015 01:46:27 GMT: verbose: -> GET undefined
server | executing query against db frontend: SELECT name, @Rid, createdAt, updatedAt FROM interaction LIMIT 500 SKIP 0
server | sending operation command for database frontend
client | POST /socket.io/?__sails_io_sdk_version=0.11.0&__sails_io_sdk_platform=browser&_sails_io_sdk_language=javascript&EIO=3&transport=polling&t=1449193587343-2&sid=dR2dsPBO2yHNz_5sAAAJ 200 7.360 ms - 2
server | Fri, 04 Dec 2015 01:46:27 GMT: silly: Subscribed to the Interaction with id=#63:13 (room :: sails_model_interaction
#63:13:update)

update to record via postman call direct to api
server | Fri, 04 Dec 2015 01:59:51 GMT: verbose: -> PUT /api/v1/interactions/%2363%3A13
server | executing query against db frontend: SELECT name, @Rid, createdAt, updatedAt FROM interaction WHERE @Rid = :param0 LIMIT 1
server | sending operation command for database frontend
server | executing query against db frontend: UPDATE interaction SET updatedAt = :paramupdatedAt0 RETURN AFTER WHERE @Rid = :param0
server | sending operation command for database frontend
server | Fri, 04 Dec 2015 01:59:51 GMT: silly: Published interaction to sails_model_interaction_#63:13:update
server | executing query against db frontend: SELECT name, @Rid, createdAt, updatedAt FROM interaction WHERE @Rid = :param0 LIMIT 1
server | sending operation command for database frontend
server | Fri, 04 Dec 2015 01:59:51 GMT: silly: res.ok() :: Sending 200 ("OK") response
server | Fri, 04 Dec 2015 01:59:51 GMT: verbose: -> PUT /api/v1/interactions/%2363%3A13 200 ( -> NaNms, 135 B)

Unable to push record into store through the socket adapter.

I receive the following error when ever a record is pushed into the store.

Uncaught Error: Assertion Failed: Passing classes to store methods has been removed. Please pass a dasherized string instead of ember-testapp@model:item:

Is this a known problem, or does anyone have a known work around?

SocketAdapter: findHasMany does not subscribe

Hi there,

I'm testing this adapter and I'm having an issue with a hasMany relationship. In my case a Page has many Content Areas. I've extended sails to add a links hash to the response, in this case like so:

page: {
    ...
    links: [
       { contentareas: "/page/2/contentareas" }
   ]
}

The adapter parses the response as expected and fetches the content areas. Due to debugging I found out that the _listenToSocket is called in buildURL, but buildURL is never called with the contentarea model in findHasMany. So the contentarea model is not subscribed, the async relationship does not automatically update. I came up with a quick fix by implementing findHasMany in sails-socket.js like so:

var get = Ember.get;

// [...]

findHasMany: function(store, record, url, relationship) {
    var host = get(this, 'host');
    var id   = get(record, 'id');
    var type = record.constructor.typeKey;

   if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') {
      url = host + url;
    }
    this._listenToSocket(relationship.type.typeKey); // <--- NEW NEW NEW
    return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
}

With this fix the async hasMany relationship automatically subscribes. As I've not yet written any adapters I'm not sure if this is a good way to solve the problem. Any thoughts? How was it thought to handle the async hasMany case in ember-data-sails (should the links hash be used?)?

Thanks, BR, toovy

Ho would I use the sails adapter when testing with Ember CLI Mirage?

I want to test my Ember app using Ember CLI Mirage. If I'm using the sails socket adapter instead of the Ember REST adapter I'm running into problems because I need the sails server to be running. How would I use Mirage and the Sails Socket Adapter together. So far I have just used the standard REST Adapter of Ember for testing.

Could not find module `ember-data-sails/config/environment

I've set everything up, created a simple user model/route in sails and ember. My sails API outputs the correct JSON and I've set up my SailsRESTAdapter.

{
  "users": [
    {
      "createdAt": "2015-08-12T10:54:00.946Z",
      "updatedAt": "2015-08-12T10:54:00.946Z",
      "id": 1
    },
    {
      "createdAt": "2015-08-12T10:54:09.329Z",
      "updatedAt": "2015-08-12T10:54:09.329Z",
      "id": 2
    },
    {
      "createdAt": "2015-08-12T10:54:13.391Z",
      "updatedAt": "2015-08-12T10:54:13.391Z",
      "id": 3
    }
  ]
}

But when i go to localhost:4200/users, i get a console error:

Error while processing route: users Could not find module ember-data-sails/config/environment imported from ember-data-sails/serializers/sails Error: Could not find module ember-data-sails/config/environment imported from ember-data-sails/serializers/sails

Any idea what this could be?

missing pubsub hook in sails

Hi,

I've been fighting with trying to get this working for a day now and just wondered if someone here might be able to help shed some light on what I'm missing. I managed to get the model set in my route in ember and set the adapter for that model to sailsSocket. When the route loads I can see sails process the request as a socket request and it returns the first 5 records of my model. All good so far.

What I can't see happening is when a record is created in sails that it is being broadcast out to the subscribing clients. I've been doing a lot of debugging in different places to try and work out where the root cause is and I've tracked it down to what looks like the fact that there is no pubsub hook registered in my sails hooks container.

Inside the create blueprint the following code just isn't ever getting fired because req._sails.hooks.pubsub doesn't exist. If I look at req._sails.hooks.sockets I can see a socket registered for my client so I think that part is working.

if ( req._sails.hooks.pubsub ) {
  if ( req.isSocket ) {
    Model.subscribe( req, newInstance );
    Model.introduce( newInstance );
  }
  Model.publishCreate( newInstance, !req.options.mirror && req );
}

I'm just wondering if there is somewhere in the config this is supposed to be switched on or am I missing a node_module somewhere?

I tried changing it to the following to see if maybe pubsub was outdated, but then all I get is an undefined error on the Model.publishCreate as if those functions aren't even registered on the models. Which makes me think even more that pubsub is basically missing in my sails app.

if ( req._sails.hooks.sockets ) {
  if ( req.isSocket ) {
    Model.subscribe( req, newInstance );
    Model.introduce( newInstance );
  }
  Model.publishCreate( newInstance, !req.options.mirror && req );
}

I realise this probably isn't an ember-data-sails issue directly, but I'm guessing the people here have a pretty good understanding of that aspect. Any assistance would be greatly appreciated.

Kind Regards
Paul

model.addedTo listener is not listed in the socket adapter

Hi I need help with getting model.addedTo to work. I'm not sure if i'm doing it correctly or if there is a better way of doing it as the message record is being added to ember data but it is not updating the template.

Here is how my model group model looks like

export default DS.Model.extend({
  users: DS.hasMany('user', {async: true}),
  messages: DS.hasMany('message', {async: true}),
  type: DS.attr('number'),
  name: DS.attr('string')
});

Here is how my message model looks like

export default DS.Model.extend({
    group: DS.belongsTo('group', {inverse: null}),
    content: DS.attr('string'),
    user: DS.belongsTo('user', {inverse: null})
});

here is my chat.js in my routes folder

export default Ember.Route.extend({
    model: function() {
        return this.store.filter('group');
    }
});

This is the tiggering event the sets off the socket.io listener
/controller/chat.js

sendMessage: function (message) {
            //console.log(message);
            Ember.$.ajax({
                url: '/api/v1/messages',
                type: 'POST',
                data: {
                    message: {
                        group: message.groupId,
                        content: message.message,
                        user: this.store.all('user').objectAt(0).id
                    }
                }
            });
        },

in my console.log i see [ed-sails] triggering event group.addedTo

I noticed that there is not listener called addedTo in the library so I made my own addedTo to my custom adapter called group.js like so

_listenToSocket: function (model) {
        var store, type;
        var eventName = camelize(model).toLowerCase();
        var socket = this.sailsSocket;
        if (socket.listenFor(eventName, true)) {
            this.notice(fmt('setting up adapter to listen for `%@` messages', model));
            store = this.container.lookup('store:main');
            type = store.modelFor(model);
            socket.on(eventName + '.created', bind(this, '_handleSocketRecordCreated', store, type));
            socket.on(eventName + '.updated', bind(this, '_handleSocketRecordUpdated', store, type));
            socket.on(eventName + '.destroyed', bind(this, '_handleSocketRecordDeleted', store, type));
            socket.on(eventName + '.addedTo', bind(this, '_handleAddedTo', store, type));
            console.log(eventName);
        }
    },
    _handleAddedTo: function(store, type, message) {
        var _this = this, payload = {};
        type.typeKey = 'message';
        Ember.$.ajax({
            url: '/api/v1/' + message.attribute + "/" + message.addedId,
            type: 'GET'
        }).then(function(response) {
            store.pushPayload(response);
        });
    }

I see that it is being added to the message model of ember-data but it's not updating the template. I'm stuck and i'm out of ideas. Is there a way i can listen to the message model and manually push the object to the template?

Thanks in advance.

Error fetching crsf token with sails and ember on different host

Hi. Thanks again for the work.
It seems your REST adapter is trying to fetch a csrf token from the ember host, not the sails host. GET requests are ok but as soon as I POST, I get

GET http://dev.planecq.com:4200/csrfToken 404 (Not Found) 

and ...:4200 is my ember host, sails is on ...:1337.

404 error http://localhost:4200/socket.io/

I've set up using the README, with ENV.APP.emberDataSails.socketUrl set to 'localhost:1337' and app.import('vendor/js/sails.io.js') added to the Brocfile, but I keep getting this error:

GET http://localhost:4200/socket.io/1/?__sails_io_sdk_version=0.10.0&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&t=1425331004329 404 (Not Found)

I'm assuming that request should be pointing to port 1337

UPDATE
I've managed to get it pointing to port 1337, by adding:

<script>
    io.sails.url = 'http://localhost:1337';
</script>

to my index.html file, but I'm still getting the same error:
GET http://localhost:1337/socket.io/1/?__sails_io_sdk_version=0.10.0&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&t=1425331004329 404 (Not Found)

If I curl 'http://localhost:1337/socket.io/1/?__sails_io_sdk_version=0.10.0&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&t=1425331004329' I get {"code":0,"message":"Transport unknown"}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.