Twipped / joi-to-swagger

A library to convert Joi schema objects into Swagger schema definitions
Other
165 stars 63 forks source link

Generate parameters array #88

Open Alonzzzo2 opened 2 years ago

Alonzzzo2 commented 2 years ago

Hi, I have this joi object: Joi.object({ userGuid: Joi.string().uuid().required(), version: Joi.string() .regex(/^\d+(.\d+){3}$/) .required(), os: Joi.string() .valid('IOS', 'ANDROID', 'CHROMEOS', 'WINDOWS', 'MACOS') .required(), endUserId: Joi.string().required(), machineId: Joi.string().required(), }).meta({ className: 'postVersionInfo' })

and I generates this schema: "postVersionInfo": { "type": "object", "properties": { "userGuid": { "type": "string", "format": "uuid" }, "version": { "type": "string", "pattern": "^\\d+(.\\d+){3}$" }, "os": { "type": "string", "enum": [ "IOS", "ANDROID", "CHROMEOS", "WINDOWS", "MACOS" ] }, "endUserId": { "type": "string" }, "machineId": { "type": "string" } }, "required": [ "userGuid", "version", "os", "endUserId", "machineId" ], "additionalProperties": false }

But in order to use in properly in swagger and to get info about each parameter, I need a joi-to-swagger to generate an array of parameters, like in this example: https://petstore.swagger.io/#/pet/uploadFile, where the parameters schema looks like: [ { "name": "petId", "in": "path", "description": "ID of pet to update", "required": true, "type": "integer", "format": "int64" }, { "name": "additionalMetadata", "in": "formData", "description": "Additional data to pass to server", "required": false, "type": "string" }, { "name": "file", "in": "formData", "description": "file to upload", "required": false, "type": "file" } ]

How can I achieve this? Thanks!

Mairu commented 2 years ago

This library is only generating the schemas and it is for OpenApi 3 not for the old version 2 which is known as Swagger.

If you check the OpenApi 3 version, you see that there is always a schema property, which is the one that is generated by this library.

Check out https://petstore3.swagger.io/ and https://petstore3.swagger.io/api/v3/openapi.json, every parameter has its own schema.

If you want to generate an array of such parameters from a Joi schema, you have to create your own function for that.

const queryParametersFromJoi = (joiSchema) => {
  const { swagger: { properties, required = [] } } = joiToSwagger(joiSchema);
  const params = [];
  Object.entries(properties).forEach(([name, schema]) => {
    const { description, ...schemaRest } = schema;
    const paramsProps = {};
    if (schemaRest.type === 'object') {
      paramsProps.style = 'deepObject';
    }
    params.push({
      in: 'query',
      name,
      required: required.includes(name),
      description,
      ...paramsProps,
      schema: schemaRest,
    });
  });
  return params;
};