Skip to content

Commit

Permalink
(docs) add zod to typecheck joke API
Browse files Browse the repository at this point in the history
  • Loading branch information
jcubic committed Oct 27, 2024
1 parent f89c101 commit 323a288
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 15 deletions.
11 changes: 10 additions & 1 deletion docs/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
"path-browserify": "^1.0.1",
"prism-react-renderer": "^2.3.0",
"react": "^18.0.0",
"react-dom": "^18.0.0"
"react-dom": "^18.0.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.5.2",
Expand Down
45 changes: 32 additions & 13 deletions docs/src/components/Terminal/joke.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,44 @@
import type { JQueryTerminal } from 'jquery.terminal';

import { z } from 'zod';

const singleJokeSchema = z.object({
type: z.literal('single'),
joke: z.string()
});

const twoPartJokeSchema = z.object({
type: z.literal('twopart'),
setup: z.string(),
delivery: z.string()
});

const jokeSchema = z.union([singleJokeSchema, twoPartJokeSchema]);

export default async function joke(this: JQueryTerminal) {
const res = await fetch('https://v2.jokeapi.dev/joke/Programming');
const data = await res.json();
const json = await res.json();

const { data, success } = jokeSchema.safeParse(json);

if (!success) {
return this.error("Error: Invalid joke data format");
}

const options = {
delay: 50,
typing: true,
keepWords: true
};

(async () => {
if (data.type == 'twopart') {
this.animation(async () => {
await this.echo(`Q: ${data.setup}`, {
delay: 50,
typing: true
});
await this.echo(`A: ${data.delivery}`, {
delay: 50,
typing: true
});
await this.echo(`Q: ${data.setup}`, options);
await this.echo(`A: ${data.delivery}`, options);
});
} else if (data.type === 'single') {
await this.echo(data.joke, {
delay: 50,
typing: true
});
await this.echo(data.joke, options);
}
})();
}

0 comments on commit 323a288

Please sign in to comment.