swagger limit错误响应代码

时间:2017-06-01 12:23:22

标签: rest swagger-ui swagger-2.0

我正在处理一个swagger 2.0文件,我想指定我的响应中的错误代码只能是USERNAME_VALIDATION_FAILED或EMAIL_VALIDATION_FAILED。这是由于swagger文件的swagger-ui视图,其中每个响应错误都可以在错误代码枚举中定义20个错误代码。 如何限制特定响应的可能错误代码?

在我的swagger文件中有请求

/register:
post:
  ...
  parameters:
      ...
  responses:
    ...
    400:
      description: Username or email validation failed, possible values for code are USERNAME_VALIDATION_FAILED, EMAIL_VALIDATION_FAILED
      schema:
        $ref: '#/definitions/Error'

我的错误看起来像

Error:
type: object
properties:
  code:
    type: string
    enum:
      - USERNAME_VALIDATION_FAILED
      - EMAIL_VALIDATION_FAILED
      - USERNAME_EXISTS
      - ...

我会建议像

这样的东西
schema:
  $ref: '#/definitions/Error.code.of(USERNAME_VALIDATION_FAILED, EMAIL_VALIDATION_FAILED)'

1 个答案:

答案 0 :(得分:1)

您无法覆盖属性的RegistrationError: type: object properties: code: type: string enum: - USERNAME_VALIDATION_FAILED - EMAIL_VALIDATION_FAILED Error: type: object properties: code: type: string enum: - USERNAME_VALIDATION_FAILED - EMAIL_VALIDATION_FAILED - USERNAME_EXISTS - ... ,因此您需要一个单独的模型:

BaseError:
  type: object
  properties:
    message:
      type: string

RegistrationError:
  allOf:
    - $ref: "#/definitions/BaseError"
    - type: object
      properties:
        code:
          type: string
          enum:
            - USERNAME_VALIDATION_FAILED
            - EMAIL_VALIDATION_FAILED

Error:
  allOf:
    - $ref: "#/definitions/BaseError"
    - type: object
      properties:
        code:
          type: string
          enum:
            - USERNAME_VALIDATION_FAILED
            - EMAIL_VALIDATION_FAILED
            - USERNAME_EXISTS
            - ...

如果错误模型具有公共属性,则可以从基础模型“继承”它们以减少代码重复:

import sun.security.pkcs11.wrapper.PKCS11;
import sun.security.pkcs11.wrapper.PKCS11Constants;

// Open provider
Provider provider = new sun.security.pkcs11.SunPKCS11(pkcs11ConfigFile);

// Do what you need
...

// Finalize the pkcs11 driver in the wrapper
PKCS11 pkcs11 = PKCS11.getInstance(library, null, null, true);
pkcs11.C_Finalize(PKCS11Constants.NULL_PTR);            

// Clean the pkcs11 driver in the wrapper to force C_Initialize next time
Field moduleMapField = PKCS11.class.getDeclaredField("moduleMap");  
moduleMapField.setAccessible(true);  
Map<?, ?> moduleMap = (Map<?, ?>) moduleMapField.get(pkcs11LibraryPath);  
moduleMap.clear();