LoginSignup
1
0

More than 5 years have passed since last update.

[Sails.js v1.0] sails.getUrlForがパラメーターを受け付けてくれないのでhelperを作った

Last updated at Posted at 2017-05-03

sails.getUrlFor

Sails.jsでもRuby on Railsのようにパラメーター付きのルーティングを定義できます。
例えば、新規登録ユーザーのEmailを認証してアカウントを有効化するために以下のようなルーティングを作ったとします。

config/routes.js
  'get /user/confirm/:id/:token': 'UserController.confirm',

アクション名からURLを取得するためにsails.getUrlForという関数が用意されていますが、Sails.jsのドキュメントによると、これ引数が一つ(target)しか定義されていません。すなわち、上記のようなルーティグに対しては、idやtokenを引数で渡すことができず、

sails.log(sails.getUrlFor('UserController.confirm'))
// => '/user/confirm/:id/:token'

と返ってきます。これでは不便なので、簡単なHelperを作りました。

generate-route-for.js

api/helpers/generate-route-for.js
module.exports = {
  friendlyName: 'GenerateRouteFor',

  description: 'Wraps sails.getRouteFor to accept params',

  sync: true,

  inputs: {
    action: {
      friendlyName: 'Route name',
      description: 'Route name',
      type: 'string',
      required: true
    },
    params: {
      friendlyName: 'Prams',
      description: 'Params for the route. A dictionaly of param names and values.',
      type: 'ref'
    }
  },

  fn: function (inputs, exits) {
    var url = sails.getUrlFor(inputs.action);
    url = _.reduce(inputs.params, function (memo, val, key) {
      // replace param names with values
      return memo.replace(':'+key, val);
    }, url);
    exits.success(url);
  }
};

こんな感じで使います。

var confirmUrl = sails.helpers.generateUrlFor({ 
  action: 'UserController.confirm', 
  params: {
    id: newUser.id, 
    token: newUser.token
  }
}).execSync()

sails.getRouteFor

Sailsは、getUrlForとは別にgetRouteForという関数も用意している。違いは何かというと、
- getUrlForはURLの文字列を返す
- getRouteForはrouteオブジェクトを返す(ex.{method: 'get', url: '/hoge/piyo'})

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0