|
| 1 | +/** |
| 2 | + * @fileoverview Require functions with the `use server` directive to be async |
| 3 | + * @author Jorge Zreik |
| 4 | + */ |
| 5 | + |
| 6 | +'use strict'; |
| 7 | + |
| 8 | +const docsUrl = require('../util/docsUrl'); |
| 9 | +const report = require('../util/report'); |
| 10 | + |
| 11 | +// ------------------------------------------------------------------------------ |
| 12 | +// Rule Definition |
| 13 | +// ------------------------------------------------------------------------------ |
| 14 | + |
| 15 | +const messages = { |
| 16 | + asyncServerAction: 'Server Actions must be async', |
| 17 | + suggestAsyncNamed: 'Make {{functionName}} an `async` function', |
| 18 | + suggestAsyncAnon: 'Make this function `async`', |
| 19 | +}; |
| 20 | + |
| 21 | +/** @type {import('eslint').Rule.RuleModule} */ |
| 22 | +module.exports = { |
| 23 | + meta: { |
| 24 | + docs: { |
| 25 | + description: 'Require functions with the `use server` directive to be async', |
| 26 | + category: 'Possible Errors', |
| 27 | + recommended: false, |
| 28 | + url: docsUrl('async-server-action'), |
| 29 | + }, |
| 30 | + |
| 31 | + messages, |
| 32 | + |
| 33 | + type: 'suggestion', |
| 34 | + hasSuggestions: true, |
| 35 | + |
| 36 | + schema: [], |
| 37 | + }, |
| 38 | + |
| 39 | + create(context) { |
| 40 | + return { |
| 41 | + ':function[async=false][generator=false]>BlockStatement>:first-child[expression.value="use server"]'(node) { |
| 42 | + const currentFunction = node.parent.parent; |
| 43 | + const parent = currentFunction.parent; |
| 44 | + const isMethod = parent.type === 'MethodDefinition' || (parent.type === 'Property' && parent.method); |
| 45 | + |
| 46 | + let name; |
| 47 | + if (currentFunction.id) { |
| 48 | + name = currentFunction.id.name; |
| 49 | + } else if (isMethod && parent.key && parent.key.type === 'Identifier') { |
| 50 | + name = parent.key.name; |
| 51 | + } |
| 52 | + |
| 53 | + const suggestMessage = name ? messages.suggestAsyncNamed : messages.suggestAsyncAnon; |
| 54 | + const data = name ? { functionName: `\`${name}\`` } : {}; |
| 55 | + report(context, messages.asyncServerAction, 'asyncServerAction', { |
| 56 | + node: currentFunction, |
| 57 | + data, |
| 58 | + suggest: [{ |
| 59 | + desc: suggestMessage, |
| 60 | + data, |
| 61 | + fix(fixer) { |
| 62 | + if (isMethod) { |
| 63 | + return fixer.insertTextBefore(parent.key, 'async '); |
| 64 | + } |
| 65 | + return fixer.insertTextBefore(currentFunction, 'async '); |
| 66 | + }, |
| 67 | + }], |
| 68 | + }); |
| 69 | + }, |
| 70 | + }; |
| 71 | + }, |
| 72 | +}; |
0 commit comments