Skip to content

Commit

Permalink
🔡 Message is now a constructor variable
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashu11-A committed Jul 6, 2024
1 parent 8798929 commit babd637
Show file tree
Hide file tree
Showing 9 changed files with 37 additions and 43 deletions.
24 changes: 15 additions & 9 deletions src/class/questions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,16 @@ import inquirer, { CheckboxQuestion, ListChoiceOptions, ListQuestion } from 'inq
import autoComplete from 'inquirer-autocomplete-standalone'
import { Page } from './pages.js'

interface QuestionsOptions {
message: string
}
export class Questions {
public readonly message

constructor({ message }: QuestionsOptions) {
this.message = message
}

async ask (message: string): Promise<string> {
const result = await inquirer.prompt({
name: 'value',
Expand All @@ -17,8 +26,7 @@ export class Questions {
return result.value
}

async select (options: { message: string, choices: ListChoiceOptions[], type?: ListQuestion['type'] | CheckboxQuestion['type'], pageName: string }): Promise<string> {
const { choices, message, pageName, type } = options
async select ({ choices, pageName, type }: { choices: ListChoiceOptions[], type?: ListQuestion['type'] | CheckboxQuestion['type'], pageName: string }): Promise<string> {
if (process.env.isTest) return choices[0].value

const pageSelect = Page.all.find((page) => page.interaction.name === pageName) as Page<PageTypes>
Expand Down Expand Up @@ -51,13 +59,12 @@ export class Questions {
new inquirer.Separator(),
...footerBar,
],
message: !['zones', null].includes(page.get()) ? `[${zone.get()?.name}] - ${message}` : message
message: !['zones', null].includes(page.get()) ? `[${zone.get()?.name}] - ${this.message}` : this.message
})
return result.value as string
}

async autoComplete<T>(options: { message: string, choices: ListChoiceOptions[], pageName: string }): Promise<T> {
const { message, choices, pageName } = options
async autoComplete<T>({ choices, pageName }: { choices: ListChoiceOptions[], pageName: string }): Promise<T> {

const pageSelect = Page.all.find((page) => page.interaction.name === pageName) as Page<PageTypes>
const footerBar: ListChoiceOptions[] = []
Expand All @@ -82,7 +89,7 @@ export class Questions {
choices.push(...footerBar)

const answer = await autoComplete({
message,
message: this.message,
async source(input) {
const filtered = choices.filter(({ name }) => name?.toLowerCase().includes(input?.toLocaleLowerCase() ?? ''))
return filtered.map(choice => {
Expand All @@ -97,13 +104,12 @@ export class Questions {
return answer as T
}

async multipleQuestions (options: { message: string, templates: string[] }): Promise<{ values: Record<string, string>; result: string }> {
const { message, templates } = options
async multipleQuestions ({ templates }: { templates: string[] }): Promise<{ values: Record<string, string>; result: string }> {

const answer = await enquirer.prompt({
name: 'value',
type: 'snippet',
message,
message: this.message,
async validate (value) {
const result = JSON.parse((value as unknown as { result: string }).result) as Record<string, string | Record<string, string>>
const values = (value as unknown as { values: string} ).values as unknown as Record<string, string>
Expand Down
14 changes: 5 additions & 9 deletions src/controller/cloudflare.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import 'dotenv/config'
import Cloudflare from 'cloudflare'
import { readFile, writeFile } from 'fs/promises'
import { Questions } from '@/class/questions.js'
import { exists } from '@/lib/exists.js'

const question = new Questions()
import Cloudflare from 'cloudflare'
import 'dotenv/config'
import { readFile, writeFile } from 'fs/promises'


export async function checker() {
Expand All @@ -13,12 +11,10 @@ export async function checker() {
let data = await exists('.env') ? await readFile('.env', { encoding: 'utf-8' }) ?? '' : ''

if ([undefined, ''].includes(process.env.CLOUDFLARE_EMAIL)) {
console.log('Email do cloudflare está indefinido!')
email = await question.ask('Email do Cloudflare')
email = await new Questions({ message: 'Email do cloudflare está indefinido!' }).ask('Email do Cloudflare')
}
if ([undefined, ''].includes(process.env.CLOUDFLARE_API_KEY)) {
console.log('Token do cloudflare está indefinido!')
key = await question.ask('Token do Cloudflare')
key = await new Questions({ message: 'Token do cloudflare está indefinido!' }).ask('Token do Cloudflare')
}


Expand Down
3 changes: 1 addition & 2 deletions src/pages/dns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ export default new Page({
type: PageTypes.Option,
requirements: [zone],
async run(options) {
const response = await new Questions().select({
message: '[🌐 DNS] O que deseja fazer?',
const response = await new Questions({ message: '[🌐 DNS] O que deseja fazer?' }).select({
pageName: options.interaction.name,
choices: [
{
Expand Down
11 changes: 5 additions & 6 deletions src/pages/dns/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { extractTypes, Properties } from '@/lib/extractTypes.js'
import { PageTypes } from '@/types/page.js'
import chalk from 'chalk'

enum Types {
enum RecordsType {
ARecord = 'A',
AAAARecord = 'AAAA',
CAARecord = 'CAA',
Expand Down Expand Up @@ -37,13 +37,12 @@ new Page({
async run(options) {
const [zone] = options.interaction.requirements
const { id } = zone.get()
const type = await new Questions().autoComplete<string>({
const type = await new Questions({ message: '🎯 Escolha o tipo de Record' }).autoComplete<string>({
pageName: options.interaction.name,
message: '🎯 Escolha o tipo de Record',
choices: Object.values(Types).map((type) => ({ value: type, name: type }))
choices: Object.values(RecordsType).map((type) => ({ value: type, name: type }))
})

const record = Object.entries(Types).find(([, typeName]) => typeName === type)?.[0] as unknown as string
const record = Object.entries(RecordsType).find(([, typeName]) => typeName === type)?.[0] as unknown as string
/**
* Caso o Record não esteja na lista será um comando.
*/
Expand Down Expand Up @@ -105,7 +104,7 @@ new Page({
return output
}) as string[]

const { result } = await new Questions().multipleQuestions({ message: `Opções para criar o Record ${type}`, templates: variables })
const { result } = await new Questions({ message: `Opções para criar um Record ${type}` }).multipleQuestions({ templates: variables })
const json = JSON.parse(result)

await client.dns.records.create(Object.assign(json, { type, path_zone_id: id, zone_id: id}))
Expand Down
3 changes: 1 addition & 2 deletions src/pages/dns/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ new Page({
*/
const sortedRecord = records.get().sort((r1, r2) => r1.type.length - r2.type.length)

const selectsRecord = await new Questions().select({
message: 'Selecione os Records para serem deletadas',
const selectsRecord = await new Questions({ message: 'Selecione os Records para serem deletadas' }).select({
pageName: options.interaction.name,
type: 'checkbox',
choices: sortedRecord.map((record) => {
Expand Down
3 changes: 1 addition & 2 deletions src/pages/dns/edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ new Page({
*/
const sortedRecord = records.get().sort((r1, r2) => r1.type.length - r2.type.length)

const selectsRecord = await new Questions().select({
message: 'Selecione os Records para serem editadas',
const selectsRecord = await new Questions({ message: 'Selecione os Records para serem editadas' }).select({
pageName: options.interaction.name,
type: 'checkbox',
choices: sortedRecord.map((record) => {
Expand Down
16 changes: 7 additions & 9 deletions src/pages/dns/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,18 @@ new Page({
requirements: [records],
async run(options) {
/**
* Para deixar o console visivelmente mais bonito
* Isso deixará o expaçamento uniforme
*/
* Para deixar o console visivelmente mais bonito
* Isso deixará o expaçamento uniforme
*/
const maxTypeLength = Math.max(...records.get().map((record) => record.type.length))
const maxNameLength = Math.max(...records.get().map((record) => record.name.length))

/**
* Colocar em ordem crescente
*/
* Colocar em ordem crescente
*/
const sortedRecord = records.get().sort((r1, r2) => r1.type.length - r2.type.length)

const selectRecord = await new Questions().select({
message: 'Selecione um Record para editar',
const selectRecord = await new Questions({ message: 'Selecione um Record para editar' }).select({
pageName: options.interaction.name,
choices: sortedRecord.map((record) => {
const paddedType = `[${record.type}]`.padEnd(maxTypeLength + 2, ' ')
Expand All @@ -39,8 +38,7 @@ new Page({
const recordName = selectRecord.split('_')[1]
const recordId = selectRecord.split('_')[2]

const action = await new Questions().select({
message: `[🔗 ${recordName}] O que deseja fazer?`,
const action = await new Questions({ message: `[🔗 ${recordName}] O que deseja fazer?` }).select({
pageName: options.interaction.name,
choices: [
{
Expand Down
3 changes: 1 addition & 2 deletions src/pages/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ export default new Page({
type: PageTypes.Option,
previous: 'zones',
async run(options) {
const result = await new Questions().select({
message: '📂 Opções disponiveis',
const result = await new Questions({ message: '📂 Opções disponiveis' }).select({
pageName: options.interaction.name,
choices: [
{
Expand Down
3 changes: 1 addition & 2 deletions src/pages/zones.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ export default new Page ({
requirements: [zones],
async run(options) {
const [zones] = options.interaction.requirements
const response = await new Questions().select({
message: '🚧 Selecione a zona que deseja modificar',
const response = await new Questions({ message: '🚧 Selecione a zona que deseja modificar' }).select({
pageName: options.interaction.name,
choices: zones.get().map((zone)=> ({
name: zone.name,
Expand Down

0 comments on commit babd637

Please sign in to comment.