LoopBack4如何从Swagger中隐藏指定API方法
在LoopBack4中隐藏Swagger文档中的特定接口
要解决x-visibility字段的TypeScript类型错误并成功隐藏/files/{filename}接口,可按以下两种方案操作:
方案1:类型断言快速绕过检查
直接在@get装饰器中对x-visibility字段使用类型断言,避免TypeScript的类型校验报错:
import {get, param} from '@loopback/rest'; export class DocumentacionController { @get('/files/{filename}', { responses: { '200': { description: '获取文件', content: {'application/octet-stream': {schema: {type: 'string', format: 'binary'}}}, }, }, // 用类型断言绕过类型检查 'x-visibility': 'undocumented' as any, }) async getFile(@param.path.string('filename') filename: string) { // 你的文件获取逻辑 return /* 文件内容 */; } }
方案2:扩展OpenAPI类型定义(推荐)
通过扩展LoopBack4的OpenAPI类型声明,让TypeScript识别自定义的x-visibility字段,无需每次都用断言:
- 在项目
src目录下创建类型声明文件openapi-extensions.d.ts - 添加以下内容:
import {OperationObject} from '@loopback/openapi-v3'; declare module '@loopback/openapi-v3' { interface OperationObject { // 扩展OperationObject,添加x-visibility字段 'x-visibility'?: 'undocumented' | string; } }
- 之后直接在
@get装饰器中使用x-visibility字段即可,不会再触发类型错误:
@get('/files/{filename}', { responses: { '200': { description: '获取文件', content: {'application/octet-stream': {schema: {type: 'string', format: 'binary'}}}, }, }, 'x-visibility': 'undocumented', })
完成上述操作后,LoopBack4生成的Swagger文档会自动隐藏该接口,符合你的安全需求。
内容的提问来源于stack exchange,提问作者Andreas Aravena
相关产品推荐
相关产品推荐

