Skip to content

Commit

Permalink
Add Zod validation to parseInput function
Browse files Browse the repository at this point in the history
  • Loading branch information
sujal-sakpal authored and rajdip-b committed Sep 1, 2024
1 parent 223cb39 commit 49ad77f
Showing 1 changed file with 44 additions and 23 deletions.
67 changes: 44 additions & 23 deletions apps/cli/src/commands/profile/create.profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { ProfileConfig } from '@/types/index.types'
import { fetchProfileConfig, writeProfileConfig } from '@/util/configuration'
import { API_BASE_URL } from '@/util/constants'
import { intro, outro, confirm, spinner, text } from '@clack/prompts'
import { z } from 'zod';

export default class CreateProfile extends BaseCommand {
private profiles: ProfileConfig
Expand Down Expand Up @@ -64,32 +65,52 @@ export default class CreateProfile extends BaseCommand {
outro(`Profile ${name} created successfully`)
}

private async parseInput(options: CommandActionData['options']): Promise<{
name: string
apiKey: string
baseUrl: string
setDefault: boolean
}> {
let { name, apiKey } = options
const { baseUrl, setDefault } = options

if (!name) {
name = await text({
message: 'Enter the name of the profile',
placeholder: 'work'
})
}

if (!apiKey) {
apiKey = await text({
message: 'Enter the API key for the profile',
placeholder: 'ks_************'
})
}
// Define the validation schemas
const nameSchema = z.string().regex(/^[a-zA-Z0-9]+$/, 'Name must contain only letters and numbers without spaces.');
const baseUrlSchema = z.string().url().or(z.string().length(0)).optional();
const apiKeySchema = z.string().regex(/^ks_[a-zA-Z0-9]+$/, 'API key must start with "ks_" and contain only letters and numbers.');
const setDefaultSchema = z.boolean().optional();

const inputSchema = z.object({
name: nameSchema,
apiKey: apiKeySchema,
baseUrl: baseUrlSchema,
setDefault: setDefaultSchema,
});

async function text(options: { message: string, placeholder: string }): Promise<string> {
// Implement your actual input collection logic here
return ''; // Dummy return, replace with actual user input
}

return { name, apiKey, baseUrl, setDefault }
private async parseInput(options: CommandActionData['options']): Promise<{
name: string,
apiKey: string,
baseUrl: string,
setDefault: boolean
}> {
let { name, apiKey, baseUrl, setDefault } = options;

if (!name) {
name = await text({
message: 'Enter the name of the profile',
placeholder: 'work'
});
}

if (!apiKey) {
apiKey = await text({
message: 'Enter the API key for the profile',
placeholder: 'ks_************'
});
}

// Validate the collected data
const parsedData = inputSchema.parse({ name, apiKey, baseUrl, setDefault });

return parsedData;
}

private async checkOverwriteExistingProfile(name: string): Promise<void> {
if (this.profiles[name]) {
const overwrite = await confirm({
Expand Down

0 comments on commit 49ad77f

Please sign in to comment.