Romeo Mihalcea
Romeo Mihalcea

Reputation: 10252

Sailsjs overwrite post action in controller

Short question, tried finding an IRC for sails for such a quick one but got lost so here goes. I have a controller with a route of '/userposts'. I know sails offers some default REST-like functionality without backend code needed but what if I want to overwrite the default POST action what would I do?

I'm forced to write a POST route such as post /userposts/create or I can overwrite the default action and post straight to /userposts which will identify my overwriting and execute it.

I hope I'm making sense. I basically want to create a custom POST route and be able to

socket.post('/userposts', {title: "Foo", content: "Bar"}, function(response){});

I tried with create but it doesn't get executed on a post to /userposts

Upvotes: 0

Views: 4002

Answers (1)

scott
scott

Reputation: 596

Sails.js provides blueprints out of the box.

These blueprints provide you with the following CRUD routes that are enabled by default

/:controller/find/:id?
/:controller/create
/:controller/update/:id
/:controller/destroy/:id

To modify the default functionality for your controllers, look at the settings in config/controllers.js

Your routes are defined within config/routes.js, in your case you have a model UserPosts and a corresponding controller named UserPostsController.

In your UserPosts controller, create a function createPost and specify the route(s) to this method

'POST /userposts/create': 'UserPostsController.createPost'

which is shorthand for

'POST /userposts/create': {
  controller: 'userposts',
  action: 'createPost'
}

you can also override the /:controller route

'POST /userposts': 'UserPostsController.createPost'

These routes will map any POST requests made to the createPost function.

For more information, be sure to check out the Sails.js documentation

Upvotes: 3

Related Questions