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 committed Jul 17, 2024
1 parent 7b210ed commit e40687e
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 @@ -10,6 +10,7 @@ import {
writeProfileConfig
} from '../../util/configuration'
import { ProfileConfig } from '../../types/index.types'
import { z } from 'zod';

export default class CreateProfile extends BaseCommand {
private profiles: ProfileConfig
Expand Down Expand Up @@ -67,32 +68,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 private 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 private 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<boolean> {
if (!!this.profiles[name]) {
const overwrite = await confirm({
Expand Down

0 comments on commit e40687e

Please sign in to comment.