Home > OS >  Can I validate the length of something by middy?
Can I validate the length of something by middy?

Time:11-20

const baseHandler: APIGatewayProxyHandlerV2 = async (event) => {
  return service.create(event.body);
}

const inputSchema = {
  type: "object",
  properties: {
    body: {
      type: "object",
      properties: {
        year: { type: "number" },
        questionId: { type: "string" },
        propSeq: { type: "number" },
        questionTitle: { type: "string" }, 
        propContent: { type: "string" },
        isTrue: { type: "boolean" },
        chapter: { type: "number" }
      },
      required: ["year", "questionId", "propSeq", "questionTitle", "propContent", "isTrue", "chapter"],
    },
  },
};

export const handler = middy(baseHandler)
  .use(jsonBodyParser())
  .use(validator({inputSchema}))
  .use(httpErrorHandler())

I'm writing AWS Lambda code on Serverless Framework. I wanted request body validator like express-validator, so I found middy. But it looks impossible to validate the length of something. I want to force the length of year to 4. for example, 2023(o), 23(x)

properties: {
  year: { type: "number", length: 4 }
}

As you guess, length property cannot be understood. I don't want to add some codes to baseHandler function to validate the length. Thank you in advance.

CodePudding user response:

Middy uses JSONSchema, so you can use anything that is compatible with JSONSchema there. You could use length, but then you'd need to switch the type to string from number, as length is not supported for number (rightfully so in my opinion). If you want to keep it as number, then probably using range-based validation is your best bet: https://json-schema.org/understanding-json-schema/reference/numeric.html#range

  • Related