Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define ESLint rule for controllers' return types #109

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"@types/node": "*",
"@typescript-eslint/eslint-plugin": "6.13.2",
"@typescript-eslint/parser": "6.13.2",
"@typescript-eslint/rule-tester": "6.13.2",
"eslint": "8.55.0",
"eslint-config-standard-with-typescript": "40.0.0",
"eslint-plugin-import": "2.29.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default class {
public async getAllCats(): Promise<Api.HttpResponseBody<object[]>> {
const cats = [{ name:'Tom' }, { name: 'Minty' }]

return {
result: cats,
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export class CatsApi {
public async getAllCats(): Promise<Api.HttpResponseBody<object[]>> {
const cats = [{ name:'Tom' }, { name: 'Minty' }]

return {
result: cats,
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export class CatsController {
public async getAllCats() {
const cats = [{ name:'Tom' }, { name: 'Minty' }]

return {
result: cats,
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export class CatsController {
public async getAllCats(): Promise<object[]> {
const cats = [{ name: 'Tom' }, { name: 'Minty' }]

return cats
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export class CatsController {
public async getAllCats(): Promise<Api.HttpResponseBody<object[]>> {
const cats = [{ name: 'Tom' }, { name: 'Minty' }]

return {
result: cats,
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { RuleTester } from '@typescript-eslint/rule-tester'
import { readFile } from 'fs/promises'
import { fileURLToPath } from 'url'
import { controllerClassMethodProperReturnType as rule } from './controller-class-method-proper-return-type.eslint-rule.js'

const invalidCases = [
{ name: 'invalid-class-anonymous', messageId: 'controller-class-not-anonymous' },
{ name: 'invalid-postfix-not-proper', messageId: 'controller-class-name-proper-postfix' },
{ name: 'invalid-return-type-missing', messageId: 'controller-class-method-explicit-return-type' },
{ name: 'invalid-return-type-not-proper', messageId: 'controller-class-method-proper-return-type' },
] as const

type InvalidCaseName = (typeof invalidCases)[number]['name']

async function getCaseCode(caseName: 'valid' | InvalidCaseName): Promise<string> {
const caseUrl = new URL(`cases/${caseName}.txt`, import.meta.url)
const casePath = fileURLToPath(caseUrl)
const caseCode = await readFile(casePath, 'utf8')

return caseCode
}

new RuleTester({ parser: '@typescript-eslint/parser' }).run('controller-class-method-proper-return-type', rule, {
valid: [
{
filename: 'cats.controller.ts',
name: 'valid',
code: await getCaseCode('valid'),
},
],
invalid: await Promise.all(
invalidCases.map(async ({ name, messageId }) => ({
name,
filename: 'cats.controller.ts',
code: await getCaseCode(name),
errors: [{ messageId }],
})),
),
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import * as utils from '@typescript-eslint/utils'

export const controllerClassMethodProperReturnType = utils.ESLintUtils.RuleCreator.withoutDocs({
defaultOptions: [],
meta: {
schema: [],
type: 'suggestion',
docs: {
description: 'Enforce proper return type of controller\'s methods',
},
messages: {
'controller-class-not-anonymous': 'Controller class must not be anonymous',
'controller-class-name-proper-postfix': "Controller class's name must end with '…Controller'",
'controller-class-method-explicit-return-type': "Controller class's methods must have an explicit return type annotation",
'controller-class-method-proper-return-type': "The return type annotation of a controller class's method must be 'Promise<Api.HttpResponseBody<…>>'",
},
},
create: (context) => ({
ClassDeclaration(classNode) {
const isControllerFile = context.filename.endsWith('controller.ts')

// Find all controller classes
if (!isControllerFile) {
return
}

// Require controller class to have a "Controller" postfix
if (classNode.id == null) {
context.report({
messageId: 'controller-class-not-anonymous',
node: classNode,
})
return
}

if (!classNode.id.name.endsWith('Controller')) {
context.report({
messageId: 'controller-class-name-proper-postfix',
node: classNode.id,
})
return
}

// Find all public methods of the class
for (const classElement of classNode.body.body) {
if (
classElement.type !== 'MethodDefinition' ||
classElement.accessibility !== 'public'
) {
continue
}

const returnTypeAnnotation = classElement.value.returnType?.typeAnnotation

// The method must have an explicit return type
// The return type must be 'Promise<Api.HttpResponseBody<…>>', with one type argument
if (!returnTypeAnnotation) {
context.report({
messageId: 'controller-class-method-explicit-return-type',
node: classElement,
})
return
}

if (
returnTypeAnnotation.type !== 'TSTypeReference' ||
returnTypeAnnotation.typeName.type !== 'Identifier' ||
returnTypeAnnotation.typeName.name !== 'Promise' ||
returnTypeAnnotation.typeArguments?.params.length !== 1 ||
returnTypeAnnotation.typeArguments.params[0].type !== 'TSTypeReference' ||
returnTypeAnnotation.typeArguments.params[0].typeName.type !== 'TSQualifiedName' ||
returnTypeAnnotation.typeArguments.params[0].typeName.left.type !== 'Identifier' ||
returnTypeAnnotation.typeArguments.params[0].typeName.left.name !== 'Api' ||
returnTypeAnnotation.typeArguments.params[0].typeName.right.name !== 'HttpResponseBody' ||
returnTypeAnnotation.typeArguments.params[0].typeArguments?.params.length !== 1
) {
context.report({
messageId: 'controller-class-method-proper-return-type',
node: returnTypeAnnotation,
})
}
}
},
}),
})