Edit Page

.publishCreate()

Broadcast a conventional message indicating that a new record has been created in this model.

Something.publishCreate( data )

Or:

  • Something.publishCreate(data, req);

Usage

Argument Type Details
1 data A dictionary of the new record's attributes and their values to announce. This may consist of any JSON-serializable data you like, but must at-minimum contain the primary key of the record (usually id).
2 req If provided, then the requesting socket will be excluded from the broadcast.

publishCreate() broadcasts to all sockets "watching" this model-- that is, those client sockets which have joined the model's "class room" via .watch())-- and uses the model's identity as the event name. publishCreate() also subscribes these "watching" client sockets to the new record using .subscribe() in order to be notified of future broadcasts from publishUpdate(), publishDestroy(), etc.

The broadcasted event data received on the client is a dictionary with the following properties:

  • verb - a constant: 'created'
  • id - the new record's id which is a or
  • data - a containing the values provided as data when publishCreate() was called from your Sails backend.

Example

In a controller action which processes signups:

var Passwords = require('machinepack-passwords');

// Encrypt a string using the BCrypt algorithm.
Passwords.encryptPassword({
  password: req.param('password'),
}).exec({
  error: function (err){ return res.serverError(err); },
  success: function (encryptedPassword){
    User.create({
      username: req.param('username'),
      passsword: encryptedPassword,
      securityQuestion: {
        whichQuestion: req.param('securityQuestionId'),
        answer: req.param('securityAnswer')
      }
    }).exec(function (err, newUser){
      if (err) return res.negotiate(err);

      // Inform logged-in administrators (if there are any) that a new user has signed up.
      // (note that we deliberately exclude the security question and encrypted password,
      //  but send everything else through.  We know this will only be received by client
      //  sockets which were allowed to `.watch()`.)
      User.publishCreate(_.omit(newUser, 'password'), req );

      // Log in.
      req.session.me = newUser.id;

      // Signup completed successfully!
      return res.ok();
    });//</User.create()>
  }
});//</Passwords.encryptPassword()>

The endpoint will respond with a simple 200 (because of res.ok()), but all "watching" client sockets (in this scenario, open browser tabs of admin users) will receive a user event:

// e.g. in the browser...
io.socket.on('user', function (event){
  switch (event.verb) {
    'created':
      // This is where code that handles this socket event should go.
      // (e.g. to update the user interface)
      console.log(event);
      // => see below for the contents of `event`
      break;
    default:
      console.warn('Unrecognized socket event (`%s`) from server:',event.verb, event);
  }
});

In this case, the logged message would look something like this:

{
  verb: 'created',
  id: 4,
  data: {
    username: 'lizzy',
    createdAt: '1808-01-19T13:00:00.000Z',
    updatedAt: '1808-01-19T13:00:00.000Z'
  }
}

Notes

  • This method works much in the same way as .message()-- it just represents a more specific use case and has a few special features as described above. For more conceptual background, see the overview on resourceful pubsub.
  • It is important to understand that this method does not actually do anything to your database-- it is purely a conventional way of announcing that changes have occurred. Underneath the covers, the resourceful pubsub methods are just using combinations of sails.sockets methods.
  • Be sure and check req.isSocket === true before passing in req to refer to the requesting socket. If used, the provided req must be from a socket request, not just any old HTTP request.
  • See also .watch() for some important security considerations.

Is something missing?

If you notice something we've missed or could be improved on, please follow this link and submit a pull request to the sails-docs repo. Once we merge it, the changes will be reflected on the website the next time it is deployed.

Sails logo
  • Home
  • Get started
  • Support
  • Documentation
  • Documentation

For a better experience on sailsjs.com, update your browser.

Documentation

Reference Concepts App structure | Upgrading Contribution guide | Tutorials More

Reference

  • Application
    • Events
    • Lifecycle
    • sails.getRouteFor()
    • sails.getUrlFor()
    • sails.lift()
    • sails.load()
    • sails.log()
    • sails.lower()
    • sails.request()
    • sails.getBaseUrl()
  • Blueprint API
    • add to
    • create
    • destroy
    • find one
    • find where
    • populate where
    • remove from
    • update
  • Command Line Interface
    • sails console
    • sails debug
    • sails generate
    • sails lift
    • sails new
    • sails version
  • Configuration
    • sails.config.*
    • sails.config.blueprints
    • sails.config.bootstrap()
    • sails.config.connections
    • sails.config.cors
    • sails.config.csrf
    • sails.config.globals
    • sails.config.http
    • sails.config.i18n
    • sails.config.log
    • sails.config.models
    • sails.config.policies
    • sails.config.routes
    • sails.config.session
    • sails.config.sockets
    • sails.config.views
  • Request (`req`)
    • req.accepted
    • req.acceptedCharsets
    • req.acceptedLanguages
    • req.body
    • req.cookies
    • req.fresh
    • req.headers
    • req.host
    • req.ip
    • req.ips
    • req.isSocket
    • req.method
    • req.options
      • req.options.values
      • req.options.where
    • req.originalUrl
    • req.params
    • req.path
    • req.protocol
    • req.query
    • req.secure
    • req.signedCookies
    • req.socket
    • req.subdomains
    • req.url
    • req.wantsJSON
    • req.xhr
    • req.accepts()
    • req.acceptsCharset()
    • req.acceptsLanguage()
    • req.allParams()
    • req.file()
    • req.get()
    • req.is()
    • req.param()
  • Response (`res`)
    • res.attachment()
    • res.badRequest()
    • res.clearCookie()
    • res.cookie()
    • res.created()
    • res.forbidden()
    • res.get()
    • res.json()
    • res.jsonp()
    • res.location()
    • res.negotiate()
    • res.notFound()
    • res.ok()
    • res.redirect()
    • res.send()
    • res.serverError()
    • res.set()
    • res.status()
    • res.type()
    • res.view()
  • Waterline (ORM)
    • Models
      • .count()
      • .create()
      • .destroy()
      • .find()
      • .findOne()
      • .findOrCreate()
      • .native()
      • .query()
      • .stream()
      • .update()
    • Populated Values
      • .add()
      • .remove()
    • Queries
      • .exec()
      • .limit()
      • .populate()
      • .skip()
      • .sort()
      • .where()
    • Records
      • .save()
      • .toJSON()
      • .toObject()
  • WebSockets
    • Resourceful PubSub
      • .message()
      • .publishAdd()
      • .publishCreate()
      • .publishDestroy()
      • .publishRemove()
      • .publishUpdate()
      • .subscribe()
      • .unsubscribe()
      • .unwatch()
      • .watch()
      • .subscribers()
    • sails.sockets
      • .addRoomMembersToRooms()
      • .blast()
      • .broadcast()
      • .getId()
      • .join()
      • .leave()
      • .leaveAll()
      • .removeRoomMembersFromRooms()
      • sails.sockets.emit()
      • sails.sockets.id()
      • sails.sockets.rooms()
      • sails.sockets.socketRooms()
      • sails.sockets.subscribers()
    • Socket Client
      • io.sails
      • io.socket
      • SailsSocket
        • Methods
        • Properties
      • io.socket.delete()
      • io.socket.get()
      • io.socket.off()
      • io.socket.on()
      • io.socket.post()
      • io.socket.put()
      • io.socket.request()

Built with Love

The Sails framework is maintained by a web & mobile studio in Austin, TX, with the help of our contributors. We created Sails in 2012 to assist us on Node.js projects. Naturally we open-sourced it. We hope it makes your life a little bit easier!

Sails:
  • What is Sails?
  • Treeline IDE
  • Contribute
  • Logos/artwork
About:
  • The Sails Company
  • Security
  • News
  • Legal
Help:
  • Get started
  • Documentation
  • Docs
  • Enterprise
  • Hire us

© 2012-2018 The Sails Company. 
The Sails framework is free and open-source under the MIT License.