next-expose
Version:
A fluent, type-safe API routing and middleware layer for the Next.js App Router.
48 lines (47 loc) • 1.32 kB
JavaScript
import { ValidationError as f } from "./errors.es.js";
import { BadRequest as u } from "./responses.es.js";
const y = (o) => async (c, d, e) => {
let a;
try {
a = await c.clone().json();
} catch {
throw new f(null, "Request body is not valid JSON.");
}
const r = await o.safeParseAsync(a);
if (!r.success)
throw new f(
{ errors: r.error.flatten().fieldErrors },
"Validation failed"
);
const t = { validatedBody: r.data };
return e(t);
}, m = (o) => async (c, d, e) => {
const a = new URL(c.url), r = {};
a.searchParams.forEach((s, i) => {
const n = r[i];
n ? Array.isArray(n) ? n.push(s) : r[i] = [n, s] : r[i] = s;
});
const t = await o.safeParseAsync(r);
if (!t.success) {
const s = {};
return t.error.issues.forEach((i) => {
const n = i.path.join(".");
s[n] || (s[n] = []), s[n].push(i.message);
}), u({ errors: s }, "Invalid query parameters");
}
const l = { query: t.data };
return e(l);
}, w = (o, c, d) => {
let e = null;
const a = o.headers.get("x-forwarded-for");
a && (e = a.split(",")[0].trim());
const r = o.headers.get("x-real-ip");
r && (e = r);
const t = o.headers.get("cf-connecting-ip");
return t && (e = t), d({ ip: e });
};
export {
w as ipAddress,
y as validate,
m as validateQuery
};