Skip to content

Mock API should match real API logic around resource selector combinations #264

@david-crespo

Description

@david-crespo

In Nexus, if you try to select something by { path: { router: '<id>' }, query: { project, vpc } }, the API will 400 because parent selectors are not allowed when the thing is specified by ID. Our validators don't error because the OpenAPI schema can't represent the valid combinations properly. But we might be able to do something sneaky here. Worst case, we can do something by hand on the console side. But ew.

function validateParams<S extends ZodSchema>(schema: S, req: Request, pathParams: PathParams) {
const rawParams = new URLSearchParams(new URL(req.url).search)
const params: [string, unknown][] = []
// Ensure numeric params like \`limit\` are parsed as numbers
for (const [name, value] of rawParams) {
params.push([name, isNaN(Number(value)) ? value : Number(value)])
}
const result = schema.safeParse({
path: pathParams,
query: Object.fromEntries(params),
})
if (result.success) {
return { params: result.data }
}
// if any of the errors come from path params, just 404 — the resource cannot
// exist if there's no valid name
const status = result.error.issues.some((e) => e.path[0] === 'path') ? 404 : 400
const error_code = status === 404 ? 'NotFound' : 'InvalidRequest'
const message = 'Zod error for params: ' + JSON.stringify(result.error)
return { paramsErr: json({ error_code, message }, { status }) }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions