-
-
Notifications
You must be signed in to change notification settings - Fork 574
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
(docs) add zod to typecheck joke API
- Loading branch information
Showing
3 changed files
with
44 additions
and
15 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
})(); | ||
} |