ヘルパーの一般的な使い方は、繰り返されるデータベースクエリをカプセル化することです。たとえば、アプリに、最後にログインした時刻を追跡するlastActiveAt
フィールドを含むUser
モデルがあるとします。このようなアプリでは、最近オンラインになったユーザーのリストを取得するのが一般的なタスクかもしれません。このクエリを複数の場所にハードコーディングするのではなく、代わりにヘルパーを作成できます。
// api/helpers/get-recent-users.js
module.exports = {
friendlyName: 'Get recent users',
description: 'Retrieve a list of users who were online most recently.',
extendedDescription: 'Use `activeSince` to only retrieve users who logged in since a certain date/time.',
inputs: {
numUsers: {
friendlyName: 'Number of users',
description: 'The maximum number of users to retrieve.',
type: 'number',
defaultsTo: 5
},
activeSince: {
description: 'Cut-off time to look for logins after, expressed as a JS timestamp.',
extendedDescription: 'Remember: A _JS timestamp_ is the number of **milliseconds** since [that fateful night in 1970](https://en.wikipedia.org/wiki/Unix_time).',
type: 'number',
defaultsTo: 0
}
},
exits: {
success: {
outputFriendlyName: 'Recent users',
outputDescription: 'An array of users who recently logged in.',
},
noUsersFound: {
description: 'Could not find any users who logged in during the specified time frame.'
}
},
fn: async function (inputs, exits) {
// Run the query
var users = await User.find({
active: true,
lastLogin: { '>': inputs.activeSince }
})
.sort('lastLogin DESC')
.limit(inputs.numUsers);
// If no users were found, trigger the `noUsersFound` exit.
if (users.length === 0) {
throw 'noUsersFound';
}
// Otherwise return the records through the `success` exit.
return exits.success(users);
}
};
デフォルトオプションを使用してアプリコード(たとえば、アクション)からこのヘルパーを呼び出すには、次のようにします。
var users = await sails.helpers.getRecentUsers();
返されるユーザーの条件を変更するには、いくつかの値を渡すことができます。
var users = await sails.helpers.getRecentUsers(50);
または、2017年の聖パトリックの日以降にログインした最新のユーザー10人を取得するには、次のようにします。
await sails.helpers.getRecentUsers(10, (new Date('2017-03-17')).getTime());
注:実行時にヘルパーに渡されるこれらの値は、**引数**またはオプションと呼ばれることがあり、ヘルパーの宣言された入力定義(例:
numUsers
およびactiveSince
)のキーの順序に対応します。
さらに、名前付きパラメーターを使用するために.with()
をチェーンします。
await sails.helpers.getRecentUsers.with({
numUsers: 10,
activeSince: (new Date('2017-03-17')).getTime()
});
最後に、noUsersFound
終了を他のエラーと同様に扱うのではなく、明示的に処理するには、.intercept()
または.tolerate()
を使用できます。
var users = await sails.helpers.getRecentUsers(10)
.tolerate('noUsersFound', ()=>{
// ... handle the case where no users were found. For example:
sails.log.verbose(
'Worth noting: Just handled a request for active users during a time frame '+
'where no users were found. Anyway, I didn\'t think this was possible, because '+
'our app is so cool and popular. But there you have it.'
);
});
var users = await sails.helpers.getRecentUsers(10)
.intercept('noUsersFound', ()=>{
return new Error('Inconceivably, no active users were found for that timeframe.');
});
ヘルパーを使用する主な利点は、1つの場所でコードを変更することで、アプリの多くの部分で機能を更新できることです。たとえば、numUsers
のデフォルト値を5
から15
に変更することで、ヘルパーを使用するあらゆる場所で返されるデフォルトリストのサイズを更新します。また、numUsers
やactiveSince
のような明確に定義された入力を使用することで、誤って無効な(つまり、数値ではない)値を使用した場合は、役立つエラーが表示されることを保証します。
上記のgetRecentUsers()
ヘルパーの例に関するいくつかの注意点
description
やfriendlyName
などのフィールドの多くは厳密には必須ではありませんが、特に複数のアプリ間でヘルパーを共有する場合は、コードの保守性を維持するのに非常に役立ちます。noUsersFound
終了は、アプリによっては役立つ場合とそうでない場合があります。ユーザーが返されなかった場合に常に特定のアクション(たとえば、別のページにリダイレクト)を実行する場合は、この終了を使用するのが良いでしょう。一方、ユーザーが返されたかどうかに基づいてビュー内のテキストを調整するだけでよい場合は、success
終了のみを使用し、アクションまたはビューコードで返された配列のlength
を確認する方が良いかもしれません。