diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..5a36021 --- /dev/null +++ b/.npmignore @@ -0,0 +1,102 @@ + See http://help.github.com/ignore-files/ for more about ignoring files. + +# compiled output +/dist +/tmp +/out-tsc +out/* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# IDEs and editors +.idea +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# IDE - VSCode +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +# misc +.sass-cache +connect.lock +typings + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + + +# Dependency directories +node_modules/ +jspm_packages/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + +# next.js build output +.next + +# Lerna +lerna-debug.log + +# System Files +.DS_Store +Thumbs.db + +/src +/bin +/template +/.vscode + +./src +./bin +./template +./.vscode \ No newline at end of file diff --git a/demo.gif b/assets/demo.gif similarity index 100% rename from demo.gif rename to assets/demo.gif diff --git a/bin/index.js b/bin/index.ts similarity index 52% rename from bin/index.js rename to bin/index.ts index 98f5c97..78597ca 100644 --- a/bin/index.js +++ b/bin/index.ts @@ -1,5 +1,4 @@ #!/usr/bin/env node -const cli = require("../src/cli"); - +import cli from "../src/cli"; cli(process.argv); diff --git a/package-lock.json b/package-lock.json index f0e7ebc..34918e3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,37 @@ "resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz", "integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==" }, + "@types/inquirer": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/@types/inquirer/-/inquirer-7.3.0.tgz", + "integrity": "sha512-wcPs5jTrZYQBzzPlvUEzBcptzO4We2sijSvkBq8oAKRMJoH8PvrmP6QQnxLB5RScNUmRfujxA+ngxD4gk4xe7Q==", + "requires": { + "@types/through": "*", + "rxjs": "^6.4.0" + } + }, + "@types/listr": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/@types/listr/-/listr-0.14.2.tgz", + "integrity": "sha512-wCipMbQr3t2UHTm90LldVp+oTBj1TX6zvpkCJcWS4o8nn6kS8SN93oUvKJAgueIRZ5M36yOlFmScqBxYH8Ajig==", + "requires": { + "@types/node": "*", + "rxjs": "^6.5.1" + } + }, + "@types/node": { + "version": "14.0.27", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.0.27.tgz", + "integrity": "sha512-kVrqXhbclHNHGu9ztnAwSncIgJv/FaxmzXJvGXNdcCpV1b8u1/Mi6z6m0vwy0LzKeXFTPLH0NzwmoJ3fNCIq0g==" + }, + "@types/through": { + "version": "0.0.30", + "resolved": "https://registry.npmjs.org/@types/through/-/through-0.0.30.tgz", + "integrity": "sha512-FvnCJljyxhPM3gkRgWmxmDZyAQSiBQQWLI0A0VFL0K7W1oRUrPJSqNO0NvTnLkBcotdlp3lKvaT0JrnyRDkzOg==", + "requires": { + "@types/node": "*" + } + }, "ansi-escapes": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.1.tgz", diff --git a/package.json b/package.json index f165bed..8ce27bc 100644 --- a/package.json +++ b/package.json @@ -3,8 +3,11 @@ "version": "1.1.1", "description": "A MongoDB Schema Generator CLI", "main": "index.js", + "files": [ + "dist" + ], "bin": { - "msc": "bin/index.js" + "msc": "dist/bin/index.js" }, "repository": { "type": "git", @@ -21,8 +24,10 @@ "author": "Arsalan Khattak ", "license": "MIT", "dependencies": { + "@types/inquirer": "^7.3.0", + "@types/listr": "^0.14.2", + "@types/node": "^14.0.27", "arg": "^4.1.3", - "chalk": "^4.1.0", "inquirer": "^7.3.3", "listr": "^0.14.3" } diff --git a/readme.md b/readme.md index 1d304f4..a644cd6 100644 --- a/readme.md +++ b/readme.md @@ -21,7 +21,7 @@ ### ✨ [Demo](https://github.com/eKhattak/mongoose-schema-cli) -![Demo](/demo.gif) +![Demo](/assets/demo.gif) ## Install diff --git a/src/cli.js b/src/cli.ts similarity index 64% rename from src/cli.js rename to src/cli.ts index 6651a6f..1520716 100644 --- a/src/cli.js +++ b/src/cli.ts @@ -1,9 +1,13 @@ -const arg = require("arg"); -const inquirer = require("inquirer"); -const schema = require("./main"); - -// export var schemaDetails = {}; -function parseArgumentsIntoOptions(rawArgs) { +import arg from "arg"; +import inquirer from "inquirer"; +import createSchema from "./main"; + +function parseArgumentsIntoOptions( + rawArgs: any[] +): { + language: boolean; + filePath: string; +} { const args = arg( { "--typescript": Boolean, @@ -17,24 +21,39 @@ function parseArgumentsIntoOptions(rawArgs) { } ); return { - language: args["--typescript"] || undefined, + language: args["--typescript"] || false, filePath: args["--filepath"] || "/", }; } -async function promptForMissingOptions(options) { +type optionsType = { + language: boolean; + filePath?: string; + schemaKeys?: number | 0; +}; + +type questionType = { + type: string; + name: string; + message: string; + default: string | boolean | number; + choices?: string[] | number[]; +}; + +async function promptForMissingOptions( + options: optionsType +): Promise<{ + language: any; + schema: any; + filePath?: string | undefined; + schemaKeys?: number | undefined; +}> { const defaultOptions = { language: "Javascript", schema: "default", }; - // if (options.skipPrompts) { - // return { - // ...options, - // template: options.template || defaultLanguage, - // }; - // } - const questions = []; + const questions: questionType[] = []; //@TODO: Temporary Disabled, Uncomment after adding Typescript Schema // if (!options.language) { // questions.push({ @@ -57,20 +76,18 @@ async function promptForMissingOptions(options) { return { ...options, language: options.language || answers.language, - mongoose: options.mongoose || answers.mongoose, schema: answers.schema, }; } async function promptForSchemaObject() { - console.log(); const defaultOptions = { name: "default", type: "String", required: true, default: "", }; - const questions = []; + const questions: questionType[] = []; questions.push({ type: "input", @@ -101,18 +118,23 @@ async function promptForSchemaObject() { default: defaultOptions.default, }); - const answers = await inquirer.prompt(questions); + const answers: { + name: string; + type: string; + required: boolean; + default: string; + } = await inquirer.prompt(questions); return { - schemaName: answers.name, + name: answers.name, type: answers.type, isRequired: answers.required, defaultValue: answers.default, }; } -async function cli(args) { - var options = parseArgumentsIntoOptions(args); +async function cli(args: string[]) { + var options: optionsType = parseArgumentsIntoOptions(args); options = await promptForMissingOptions(options); const { schemaKeys } = await inquirer.prompt({ @@ -122,19 +144,20 @@ async function cli(args) { default: 0, }); - // Get Schema Keys' Input - const schemaKeyValues = []; + const schemaKeyValues: { + name: string; + type: string; + isRequired: boolean; + defaultValue: string; + }[] = []; for (let i = 0; i < schemaKeys; i++) { const objectValues = await promptForSchemaObject(); schemaKeyValues.push(objectValues); } - options = { - ...options, - schemaKeys, - }; + var schema = { ...schemaKeys }; - await schema(options, schemaKeyValues); + await createSchema(schema, schemaKeyValues); } -module.exports = cli; +export default cli; diff --git a/src/main.js b/src/main.js deleted file mode 100644 index 50b2da3..0000000 --- a/src/main.js +++ /dev/null @@ -1,40 +0,0 @@ -const path = require("path"); -const fs = require("fs"); -const { promisify } = require("util"); -const Listr = require("listr"); -const schema = require("../template"); -const chalk = require("chalk"); - -const writeFile = promisify(fs.writeFile); -const appendFile = promisify(fs.appendFile); - -async function createSchema(options, schemaKeyValues) { - const schemaOptions = { - ...options, - dirPath: path.resolve(__dirname, "../template"), - outPath: path.resolve(process.cwd(), `./${options.schema}.js`), - }; - - console.log(); - - const tasks = new Listr([ - { - title: "Creating Schema", - task: async () => - await createObjects(schemaOptions.outPath, schemaKeyValues), - }, - ]); - - await tasks.run(); - console.log(chalk.green("DONE!"), "Schema Generated"); -} - -async function createObjects(outPath, schemaKeyValues) { - await writeFile(outPath, schema.schemaTop()); - for (let i = 0; i < schemaKeyValues.length; i++) { - await appendFile(outPath, schema.createSchemaObject(schemaKeyValues[i])); - } - await appendFile(outPath, schema.schemaBottom()); -} - -module.exports = createSchema; diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..2fb5880 --- /dev/null +++ b/src/main.ts @@ -0,0 +1,52 @@ +import path from "path"; +import fs from "fs"; +import { promisify } from "util"; +import Listr from "listr"; +import { createSchemaObject, schemaTop, schemaBottom } from "../template"; + +const writeFile = promisify(fs.writeFile); +const appendFile = promisify(fs.appendFile); + +type schemaKeyValueType = { + name: string; + type: string; + isRequired: boolean; + defaultValue: string; +}; + +async function createSchema( + schema: string, + schemaKeyValues: schemaKeyValueType[] +) { + const schemaOptions = { + // ...options, + dirPath: path.resolve(__dirname, "../template"), + outPath: path.resolve(process.cwd(), `./${schema}.js`), + }; + + console.log(); + + const tasks = new Listr([ + { + title: "Creating Schema", + task: async () => + await createObjects(schemaOptions.outPath, schemaKeyValues), + }, + ]); + + await tasks.run(); + console.log("DONE! Schema Generated"); +} + +async function createObjects( + outPath: string, + schemaKeyValues: schemaKeyValueType[] +) { + await writeFile(outPath, schemaTop()); + for (let i = 0; i < schemaKeyValues.length; i++) { + await appendFile(outPath, createSchemaObject(schemaKeyValues[i])); + } + await appendFile(outPath, schemaBottom()); +} + +export default createSchema; diff --git a/template/index.js b/template/index.ts similarity index 50% rename from template/index.js rename to template/index.ts index 00a20ee..e7122ed 100644 --- a/template/index.js +++ b/template/index.ts @@ -1,7 +1,12 @@ -function createSchemaObject(options) { - const { schemaName, type, isRequired, defaultValue } = options; +export function createSchemaObject(options: { + name: string; + type: string; + isRequired: boolean; + defaultValue: string; +}) { + const { name, type, isRequired, defaultValue } = options; return ` - ${schemaName}: { + ${name}: { type: ${type}, required: ${isRequired}, default: "${defaultValue}" @@ -9,7 +14,7 @@ function createSchemaObject(options) { `; } -function schemaTop() { +export function schemaTop() { return ` const mongoose = require("mongoose"); const Schema = mongoose.Schema; @@ -18,7 +23,7 @@ const userSchema = new Schema({ `; } -function schemaBottom() { +export function schemaBottom() { return ` timestamps: { createdAt: "created_at", updatedAt: "updated_at" } }); @@ -26,8 +31,8 @@ module.exports = userSchema; `; } -module.exports = { - createSchemaObject, - schemaTop, - schemaBottom, -}; +// module.exports = { +// createSchemaObject, +// schemaTop, +// schemaBottom, +// }; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..834690b --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,69 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Basic Options */ + // "incremental": true, /* Enable incremental compilation */ + "target": "ES2015" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, + "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, + // "lib": [], /* Specify library files to be included in the compilation. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + // "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + // "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./dist" /* Redirect output structure to the directory. */, + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true /* Enable all strict type-checking options. */, + // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + + /* Advanced Options */ + "skipLibCheck": true /* Skip type checking of declaration files. */, + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + } +}