Skip to content

Commit

Permalink
feat: gtin validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Schlauer-Hax committed Mar 29, 2024
1 parent 281c1b6 commit 07471f7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
2 changes: 1 addition & 1 deletion deno.jsonc
@@ -1,6 +1,6 @@
{
"imports": {
"webgen/": "https://raw.githubusercontent.com/lucsoft/WebGen/e7cdd13/",
"webgen/": "https://raw.githubusercontent.com/lucsoft/WebGen/d389a5b/",
// "webgen/": "../WebGen/",
"std/": "https://deno.land/std@0.221.0/",
"shared/": "./pages/shared/"
Expand Down
27 changes: 19 additions & 8 deletions spec/music.ts
@@ -1,3 +1,4 @@
import { sumOf } from "std/collections/mod.ts";
import { zod } from "webgen/zod.ts";

export const DATE_PATTERN = /\d\d\d\d-\d\d-\d\d/;
Expand Down Expand Up @@ -66,10 +67,16 @@ export const song = zod.object({
.refine(({ instrumental, explicit }) => !(instrumental && explicit), "Can't have an explicit instrumental song");

export const pureDrop = zod.object({
upc: zod.string().nullable()
.transform((x) => x ? x.trim() : x)
.transform((x) => x ? x : null)
.refine((x) => x == null || [12, 13].includes(x.length), { message: "Not a valid UPC" }),
upc: zod.string().trim().max(0).nullable().or(
zod.string()
.trim()
.min(12, { message: "UPC/EAN: Invalid length" })
.max(13, { message: "UPC/EAN: Invalid length" })
.regex(/^\d+$/, { message: "UPC/EAN: Not a number" })
.refine((gtin) => parseInt(gtin.slice(-1), 10) === (10 - (sumOf(gtin.slice(0, -1).split("").map((digit, index) => parseInt(digit, 10) * ((16 - gtin.length + index) % 2 === 0 ? 3 : 1)), (x) => x) % 10)) % 10, {
message: "UPC/EAN: Invalid",
}),
),
title: userString,
artists: artist.array().refine((x) => x.some(([, , type]) => type == "PRIMARY"), { message: "At least one primary artist is required" }),
release: zod.string().regex(DATE_PATTERN, { message: "Not a date" }),
Expand All @@ -91,10 +98,14 @@ export const drop = pureDrop
}));

const pageOne = zod.object({
upc: zod.string().nullable()
.transform((x) => x ? x.trim() : x)
.transform((x) => x ? x : null)
.refine((x) => x == null || [12, 13].includes(x.length), { message: "Not a valid UPC" }),
upc: zod.string()
.trim()
.min(12, { message: "UPC/EAN: Invalid length" })
.max(13, { message: "UPC/EAN: Invalid length" })
.regex(/^\d+$/, { message: "UPC/EAN: Not a number" })
.refine((gtin) => parseInt(gtin.slice(-1), 10) === (10 - (sumOf(gtin.slice(0, -1).split("").map((digit, index) => parseInt(digit, 10) * ((16 - gtin.length + index) % 2 === 0 ? 3 : 1)), (x) => x) % 10)) % 10, {
message: "UPC/EAN: Invalid checksum",
}).or(zod.string().trim().max(0, { message: "UPC/EAN: Invalid" }).nullable()),
});

const pageTwo = zod.object({
Expand Down

0 comments on commit 07471f7

Please sign in to comment.