[
  {
    "path": "DockerExample/.dockerignore",
    "content": "node_modules\nnpm-debug.log\nbuild\n.vscode"
  },
  {
    "path": "DockerExample/.gitignore",
    "content": "/build\n/node_modules"
  },
  {
    "path": "DockerExample/.prettierrc",
    "content": "{\n    \"singleQuote\": true,\n    \"printWidth\": 200,\n    \"proseWrap\": \"always\",\n    \"tabWidth\": 4,\n    \"useTabs\": false,\n    \"trailingComma\": \"none\",\n    \"bracketSpacing\": true,\n    \"jsxBracketSameLine\": false,\n    \"semi\": true\n}\n"
  },
  {
    "path": "DockerExample/.vscode/settings.json",
    "content": "{\n    \"editor.defaultFormatter\": \"esbenp.prettier-vscode\",\n    \"editor.bracketPairColorization.enabled\": true,\n    \"editor.formatOnSave\": true,\n    \"editor.formatOnPaste\": true,\n    \"editor.wordWrap\": \"on\"\n}\n"
  },
  {
    "path": "DockerExample/Dockerfile",
    "content": "FROM node:17\n\n# Working dir\nWORKDIR /usr/src/app\n\n# Copy files from Build\nCOPY package*.json ./\n\n# Install Globals\nRUN npm install prettier -g\n\n# Install Files\nRUN npm install \n\n# Copy SRC\nCOPY . .\n\n# Build\nRUN npm run build\n\n# Open Port\nEXPOSE 1337\n\n# Docker Command to Start Service\nCMD [ \"node\", \"build/server.js\" ]\n"
  },
  {
    "path": "DockerExample/package.json",
    "content": "{\n  \"name\": \"joi-example\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"src/server.ts\",\n  \"scripts\": {\n    \"build\": \"rm -rf build && prettier --write src/ && tsc\"\n  },\n  \"author\": \"\",\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"express\": \"^4.17.2\",\n    \"joi\": \"^17.5.0\",\n    \"yup\": \"^0.32.11\"\n  },\n  \"devDependencies\": {\n    \"@types/express\": \"^4.17.13\",\n    \"typescript\": \"^4.5.4\"\n  }\n}\n"
  },
  {
    "path": "DockerExample/src/controllers/joi.ts",
    "content": "import { NextFunction, Request, Response } from 'express';\nimport { IJoiData } from '../interfaces/joi';\n\nconst joiSampleRoute = (req: Request, res: Response, next: NextFunction) => {\n    const data = req.body as IJoiData;\n\n    return res.status(200).json({\n        data\n    });\n};\n\nexport default { joiSampleRoute };\n"
  },
  {
    "path": "DockerExample/src/controllers/yup.ts",
    "content": "import { NextFunction, Request, Response } from 'express';\nimport { IYupData } from '../interfaces/yup';\n\nconst yupSampleRoute = (req: Request, res: Response, next: NextFunction) => {\n    return res.status(200).json({\n        data: res.locals.data as IYupData\n    });\n};\n\nexport default { yupSampleRoute };\n"
  },
  {
    "path": "DockerExample/src/interfaces/joi.ts",
    "content": "export interface IJoiData {\n    username: string;\n    password: string;\n    email: string;\n    birth_year?: number;\n}\n"
  },
  {
    "path": "DockerExample/src/interfaces/yup.ts",
    "content": "export interface IYupData {\n    name: string;\n    age: number;\n    email?: string | undefined;\n    website?: string | null | undefined;\n    createdOn: Date;\n}\n"
  },
  {
    "path": "DockerExample/src/middleware/joi.ts",
    "content": "import Joi, { ObjectSchema } from 'joi';\nimport { NextFunction, Request, Response } from 'express';\nimport { IJoiData } from '../interfaces/joi';\n\nexport const ValidateJoi = (schema: ObjectSchema) => {\n    return async (req: Request, res: Response, next: NextFunction) => {\n        try {\n            await schema.validateAsync(req.body);\n\n            next();\n        } catch (error) {\n            console.error(error);\n\n            return res.status(422).json({ error });\n        }\n    };\n};\n\nexport const Schemas = {\n    data: Joi.object<IJoiData>({\n        username: Joi.string().alphanum().min(3).max(15).required(),\n        password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).required(),\n        email: Joi.string()\n            .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })\n            .required(),\n        birth_year: Joi.number().integer().min(1900).max(2013)\n    })\n};\n"
  },
  {
    "path": "DockerExample/src/middleware/yup.ts",
    "content": "import { object, string, number, date, AnyObjectSchema } from 'yup';\nimport { NextFunction, Request, Response } from 'express';\n\nexport const ValidateYup = (schema: AnyObjectSchema) => {\n    return async (req: Request, res: Response, next: NextFunction) => {\n        try {\n            const data = await schema.validate(req.body);\n\n            console.log(data);\n\n            next();\n        } catch (error) {\n            console.error(error);\n\n            return res.status(422).json({ error });\n        }\n    };\n};\n\nexport const Schemas = {\n    data: object().shape({\n        name: string().required(),\n        age: number().required().positive().integer(),\n        email: string().email(),\n        website: string().url(),\n        createdOn: date().default(() => new Date())\n    })\n};\n"
  },
  {
    "path": "DockerExample/src/routes/joi.ts",
    "content": "import express from 'express';\nimport controller from '../controllers/joi';\nimport { Schemas, ValidateJoi } from '../middleware/joi';\n\nconst router = express.Router();\n\nrouter.post('/', ValidateJoi(Schemas.data), controller.joiSampleRoute);\n\nexport = router;\n"
  },
  {
    "path": "DockerExample/src/routes/yup.ts",
    "content": "import express from 'express';\nimport controller from '../controllers/yup';\nimport { Schemas, ValidateYup } from '../middleware/yup';\n\nconst router = express.Router();\n\nrouter.post('/', ValidateYup(Schemas.data), controller.yupSampleRoute);\n\nexport = router;\n"
  },
  {
    "path": "DockerExample/src/server.ts",
    "content": "import http from 'http';\nimport express from 'express';\nimport joiRoutes from './routes/joi';\nimport yupRoutes from './routes/yup';\n\nconst router = express();\n\n/** Log the request */\nrouter.use((req, res, next) => {\n    /** Log the req */\n    console.info(`METHOD: [${req.method}] - URL: [${req.url}] - IP: [${req.socket.remoteAddress}]`);\n\n    res.on('finish', () => {\n        /** Log the res */\n        console.info(`METHOD: [${req.method}] - URL: [${req.url}] - STATUS: [${res.statusCode}] - IP: [${req.socket.remoteAddress}]`);\n    });\n\n    next();\n});\n\nrouter.use(express.urlencoded({ extended: true }));\nrouter.use(express.json());\n\n/** Rules of our API */\nrouter.use((req, res, next) => {\n    res.header('Access-Control-Allow-Origin', '*');\n    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');\n\n    if (req.method == 'OPTIONS') {\n        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');\n        return res.status(200).json({});\n    }\n\n    next();\n});\n\n/** Routes */\nrouter.use('/joi', joiRoutes);\nrouter.use('/yup', yupRoutes);\n\n/** Error handling */\nrouter.use((req, res, next) => {\n    const error = new Error('Not found');\n\n    return res.status(404).json({\n        message: error.message\n    });\n});\n\nconst httpServer = http.createServer(router);\nhttpServer.listen(1337, () => console.info('Server is running on port 1337 ...'));\n"
  },
  {
    "path": "DockerExample/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    /* Visit https://aka.ms/tsconfig.json to read more about this file */\n\n    /* Projects */\n    // \"incremental\": true,                              /* Enable incremental compilation */\n    // \"composite\": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */\n    // \"tsBuildInfoFile\": \"./\",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */\n    // \"disableSourceOfProjectReferenceRedirect\": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */\n    // \"disableSolutionSearching\": true,                 /* Opt a project out of multi-project reference checking when editing. */\n    // \"disableReferencedProjectLoad\": true,             /* Reduce the number of projects loaded automatically by TypeScript. */\n\n    /* Language and Environment */\n    \"target\": \"es2016\",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */\n    // \"lib\": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */\n    // \"jsx\": \"preserve\",                                /* Specify what JSX code is generated. */\n    // \"experimentalDecorators\": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */\n    // \"emitDecoratorMetadata\": true,                    /* Emit design-type metadata for decorated declarations in source files. */\n    // \"jsxFactory\": \"\",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */\n    // \"jsxFragmentFactory\": \"\",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */\n    // \"jsxImportSource\": \"\",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */\n    // \"reactNamespace\": \"\",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */\n    // \"noLib\": true,                                    /* Disable including any library files, including the default lib.d.ts. */\n    // \"useDefineForClassFields\": true,                  /* Emit ECMAScript-standard-compliant class fields. */\n\n    /* Modules */\n    \"module\": \"commonjs\",                                /* Specify what module code is generated. */\n    // \"rootDir\": \"./\",                                  /* Specify the root folder within your source files. */\n    // \"moduleResolution\": \"node\",                       /* Specify how TypeScript looks up a file from a given module specifier. */\n    // \"baseUrl\": \"./\",                                  /* Specify the base directory to resolve non-relative module names. */\n    // \"paths\": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */\n    // \"rootDirs\": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */\n    // \"typeRoots\": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */\n    // \"types\": [],                                      /* Specify type package names to be included without being referenced in a source file. */\n    // \"allowUmdGlobalAccess\": true,                     /* Allow accessing UMD globals from modules. */\n    // \"resolveJsonModule\": true,                        /* Enable importing .json files */\n    // \"noResolve\": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */\n\n    /* JavaScript Support */\n    // \"allowJs\": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */\n    // \"checkJs\": true,                                  /* Enable error reporting in type-checked JavaScript files. */\n    // \"maxNodeModuleJsDepth\": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */\n\n    /* Emit */\n    // \"declaration\": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */\n    // \"declarationMap\": true,                           /* Create sourcemaps for d.ts files. */\n    // \"emitDeclarationOnly\": true,                      /* Only output d.ts files and not JavaScript files. */\n    // \"sourceMap\": true,                                /* Create source map files for emitted JavaScript files. */\n    // \"outFile\": \"./\",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */\n    \"outDir\": \"./build\",                                   /* Specify an output folder for all emitted files. */\n    // \"removeComments\": true,                           /* Disable emitting comments. */\n    // \"noEmit\": true,                                   /* Disable emitting files from a compilation. */\n    // \"importHelpers\": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */\n    // \"importsNotUsedAsValues\": \"remove\",               /* Specify emit/checking behavior for imports that are only used for types */\n    // \"downlevelIteration\": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */\n    // \"sourceRoot\": \"\",                                 /* Specify the root path for debuggers to find the reference source code. */\n    // \"mapRoot\": \"\",                                    /* Specify the location where debugger should locate map files instead of generated locations. */\n    // \"inlineSourceMap\": true,                          /* Include sourcemap files inside the emitted JavaScript. */\n    // \"inlineSources\": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */\n    // \"emitBOM\": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */\n    // \"newLine\": \"crlf\",                                /* Set the newline character for emitting files. */\n    // \"stripInternal\": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */\n    // \"noEmitHelpers\": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */\n    // \"noEmitOnError\": true,                            /* Disable emitting files if any type checking errors are reported. */\n    // \"preserveConstEnums\": true,                       /* Disable erasing `const enum` declarations in generated code. */\n    // \"declarationDir\": \"./\",                           /* Specify the output directory for generated declaration files. */\n    // \"preserveValueImports\": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */\n\n    /* Interop Constraints */\n    // \"isolatedModules\": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */\n    // \"allowSyntheticDefaultImports\": true,             /* Allow 'import x from y' when a module doesn't have a default export. */\n    \"esModuleInterop\": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */\n    // \"preserveSymlinks\": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */\n    \"forceConsistentCasingInFileNames\": true,            /* Ensure that casing is correct in imports. */\n\n    /* Type Checking */\n    \"strict\": true,                                      /* Enable all strict type-checking options. */\n    // \"noImplicitAny\": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */\n    // \"strictNullChecks\": true,                         /* When type checking, take into account `null` and `undefined`. */\n    // \"strictFunctionTypes\": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */\n    // \"strictBindCallApply\": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */\n    // \"strictPropertyInitialization\": true,             /* Check for class properties that are declared but not set in the constructor. */\n    // \"noImplicitThis\": true,                           /* Enable error reporting when `this` is given the type `any`. */\n    // \"useUnknownInCatchVariables\": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */\n    // \"alwaysStrict\": true,                             /* Ensure 'use strict' is always emitted. */\n    // \"noUnusedLocals\": true,                           /* Enable error reporting when a local variables aren't read. */\n    // \"noUnusedParameters\": true,                       /* Raise an error when a function parameter isn't read */\n    // \"exactOptionalPropertyTypes\": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */\n    // \"noImplicitReturns\": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */\n    // \"noFallthroughCasesInSwitch\": true,               /* Enable error reporting for fallthrough cases in switch statements. */\n    // \"noUncheckedIndexedAccess\": true,                 /* Include 'undefined' in index signature results */\n    // \"noImplicitOverride\": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */\n    // \"noPropertyAccessFromIndexSignature\": true,       /* Enforces using indexed accessors for keys declared using an indexed type */\n    // \"allowUnusedLabels\": true,                        /* Disable error reporting for unused labels. */\n    // \"allowUnreachableCode\": true,                     /* Disable error reporting for unreachable code. */\n\n    /* Completeness */\n    // \"skipDefaultLibCheck\": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */\n    \"skipLibCheck\": true                                 /* Skip type checking all .d.ts files. */\n  },\n  \"include\": [\"src/**/*.ts\"]\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 Saman Arif\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "ValidationByJoiExample/.gitignore",
    "content": "/build\n/node_modules"
  },
  {
    "path": "ValidationByJoiExample/.prettierrc",
    "content": "{\n    \"singleQuote\": true,\n    \"printWidth\": 200,\n    \"proseWrap\": \"always\",\n    \"tabWidth\": 4,\n    \"useTabs\": false,\n    \"trailingComma\": \"none\",\n    \"bracketSpacing\": true,\n    \"jsxBracketSameLine\": false,\n    \"semi\": true\n}\n"
  },
  {
    "path": "ValidationByJoiExample/.vscode/settings.json",
    "content": "{\n    \"editor.defaultFormatter\": \"esbenp.prettier-vscode\",\n    \"editor.bracketPairColorization.enabled\": true,\n    \"editor.formatOnSave\": true,\n    \"editor.formatOnPaste\": true,\n    \"editor.wordWrap\": \"on\"\n}\n"
  },
  {
    "path": "ValidationByJoiExample/package.json",
    "content": "{\n  \"name\": \"joi-example\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"src/server.ts\",\n  \"scripts\": {\n    \"build\": \"rm -rf build && prettier --write src/ && tsc\"\n  },\n  \"author\": \"\",\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"express\": \"^4.17.2\",\n    \"joi\": \"^17.5.0\",\n    \"yup\": \"^0.32.11\"\n  },\n  \"devDependencies\": {\n    \"@types/express\": \"^4.17.13\",\n    \"typescript\": \"^4.5.4\"\n  }\n}\n"
  },
  {
    "path": "ValidationByJoiExample/src/controllers/joi.ts",
    "content": "import { NextFunction, Request, Response } from 'express';\nimport { IJoiData } from '../interfaces/joi';\n\nconst joiSampleRoute = (req: Request, res: Response, next: NextFunction) => {\n    const data = req.body as IJoiData;\n\n    return res.status(200).json({\n        data\n    });\n};\n\nexport default { joiSampleRoute };\n"
  },
  {
    "path": "ValidationByJoiExample/src/controllers/yup.ts",
    "content": "import { NextFunction, Request, Response } from 'express';\nimport { IYupData } from '../interfaces/yup';\n\nconst yupSampleRoute = (req: Request, res: Response, next: NextFunction) => {\n    return res.status(200).json({\n        data: res.locals.data as IYupData\n    });\n};\n\nexport default { yupSampleRoute };\n"
  },
  {
    "path": "ValidationByJoiExample/src/interfaces/joi.ts",
    "content": "export interface IJoiData {\n    username: string;\n    password: string;\n    email: string;\n    birth_year?: number;\n}\n"
  },
  {
    "path": "ValidationByJoiExample/src/interfaces/yup.ts",
    "content": "export interface IYupData {\n    name: string;\n    age: number;\n    email?: string | undefined;\n    website?: string | null | undefined;\n    createdOn: Date;\n}\n"
  },
  {
    "path": "ValidationByJoiExample/src/middleware/joi.ts",
    "content": "import Joi, { ObjectSchema } from 'joi';\nimport { NextFunction, Request, Response } from 'express';\nimport { IJoiData } from '../interfaces/joi';\n\nexport const ValidateJoi = (schema: ObjectSchema) => {\n    return async (req: Request, res: Response, next: NextFunction) => {\n        try {\n            await schema.validateAsync(req.body);\n\n            next();\n        } catch (error) {\n            console.error(error);\n\n            return res.status(422).json({ error });\n        }\n    };\n};\n\nexport const Schemas = {\n    data: Joi.object<IJoiData>({\n        username: Joi.string().alphanum().min(3).max(15).required(),\n        password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).required(),\n        email: Joi.string()\n            .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })\n            .required(),\n        birth_year: Joi.number().integer().min(1900).max(2013)\n    })\n};\n"
  },
  {
    "path": "ValidationByJoiExample/src/middleware/yup.ts",
    "content": "import { object, string, number, date, AnyObjectSchema } from 'yup';\nimport { NextFunction, Request, Response } from 'express';\n\nexport const ValidateYup = (schema: AnyObjectSchema) => {\n    return async (req: Request, res: Response, next: NextFunction) => {\n        try {\n            const data = await schema.validate(req.body);\n\n            console.log(data);\n\n            next();\n        } catch (error) {\n            console.error(error);\n\n            return res.status(422).json({ error });\n        }\n    };\n};\n\nexport const Schemas = {\n    data: object().shape({\n        name: string().required(),\n        age: number().required().positive().integer(),\n        email: string().email(),\n        website: string().url(),\n        createdOn: date().default(() => new Date())\n    })\n};\n"
  },
  {
    "path": "ValidationByJoiExample/src/routes/joi.ts",
    "content": "import express from 'express';\nimport controller from '../controllers/joi';\nimport { Schemas, ValidateJoi } from '../middleware/joi';\n\nconst router = express.Router();\n\nrouter.post('/', ValidateJoi(Schemas.data), controller.joiSampleRoute);\n\nexport = router;\n"
  },
  {
    "path": "ValidationByJoiExample/src/routes/yup.ts",
    "content": "import express from 'express';\nimport controller from '../controllers/yup';\nimport { Schemas, ValidateYup } from '../middleware/yup';\n\nconst router = express.Router();\n\nrouter.post('/', ValidateYup(Schemas.data), controller.yupSampleRoute);\n\nexport = router;\n"
  },
  {
    "path": "ValidationByJoiExample/src/server.ts",
    "content": "import http from 'http';\nimport express from 'express';\nimport joiRoutes from './routes/joi';\nimport yupRoutes from './routes/yup';\n\nconst router = express();\n\n/** Log the request */\nrouter.use((req, res, next) => {\n    /** Log the req */\n    console.info(`METHOD: [${req.method}] - URL: [${req.url}] - IP: [${req.socket.remoteAddress}]`);\n\n    res.on('finish', () => {\n        /** Log the res */\n        console.info(`METHOD: [${req.method}] - URL: [${req.url}] - STATUS: [${res.statusCode}] - IP: [${req.socket.remoteAddress}]`);\n    });\n\n    next();\n});\n\nrouter.use(express.urlencoded({ extended: true }));\nrouter.use(express.json());\n\n/** Rules of our API */\nrouter.use((req, res, next) => {\n    res.header('Access-Control-Allow-Origin', '*');\n    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');\n\n    if (req.method == 'OPTIONS') {\n        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');\n        return res.status(200).json({});\n    }\n\n    next();\n});\n\n/** Routes */\nrouter.use('/joi', joiRoutes);\nrouter.use('/yup', yupRoutes);\n\n/** Error handling */\nrouter.use((req, res, next) => {\n    const error = new Error('Not found');\n\n    return res.status(404).json({\n        message: error.message\n    });\n});\n\nconst httpServer = http.createServer(router);\nhttpServer.listen(1337, () => console.info('Server is running on port 1337 ...'));\n"
  },
  {
    "path": "ValidationByJoiExample/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    /* Visit https://aka.ms/tsconfig.json to read more about this file */\n\n    /* Projects */\n    // \"incremental\": true,                              /* Enable incremental compilation */\n    // \"composite\": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */\n    // \"tsBuildInfoFile\": \"./\",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */\n    // \"disableSourceOfProjectReferenceRedirect\": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */\n    // \"disableSolutionSearching\": true,                 /* Opt a project out of multi-project reference checking when editing. */\n    // \"disableReferencedProjectLoad\": true,             /* Reduce the number of projects loaded automatically by TypeScript. */\n\n    /* Language and Environment */\n    \"target\": \"es2016\",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */\n    // \"lib\": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */\n    // \"jsx\": \"preserve\",                                /* Specify what JSX code is generated. */\n    // \"experimentalDecorators\": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */\n    // \"emitDecoratorMetadata\": true,                    /* Emit design-type metadata for decorated declarations in source files. */\n    // \"jsxFactory\": \"\",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */\n    // \"jsxFragmentFactory\": \"\",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */\n    // \"jsxImportSource\": \"\",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */\n    // \"reactNamespace\": \"\",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */\n    // \"noLib\": true,                                    /* Disable including any library files, including the default lib.d.ts. */\n    // \"useDefineForClassFields\": true,                  /* Emit ECMAScript-standard-compliant class fields. */\n\n    /* Modules */\n    \"module\": \"commonjs\",                                /* Specify what module code is generated. */\n    // \"rootDir\": \"./\",                                  /* Specify the root folder within your source files. */\n    // \"moduleResolution\": \"node\",                       /* Specify how TypeScript looks up a file from a given module specifier. */\n    // \"baseUrl\": \"./\",                                  /* Specify the base directory to resolve non-relative module names. */\n    // \"paths\": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */\n    // \"rootDirs\": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */\n    // \"typeRoots\": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */\n    // \"types\": [],                                      /* Specify type package names to be included without being referenced in a source file. */\n    // \"allowUmdGlobalAccess\": true,                     /* Allow accessing UMD globals from modules. */\n    // \"resolveJsonModule\": true,                        /* Enable importing .json files */\n    // \"noResolve\": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */\n\n    /* JavaScript Support */\n    // \"allowJs\": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */\n    // \"checkJs\": true,                                  /* Enable error reporting in type-checked JavaScript files. */\n    // \"maxNodeModuleJsDepth\": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */\n\n    /* Emit */\n    // \"declaration\": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */\n    // \"declarationMap\": true,                           /* Create sourcemaps for d.ts files. */\n    // \"emitDeclarationOnly\": true,                      /* Only output d.ts files and not JavaScript files. */\n    // \"sourceMap\": true,                                /* Create source map files for emitted JavaScript files. */\n    // \"outFile\": \"./\",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */\n    \"outDir\": \"./build\",                                   /* Specify an output folder for all emitted files. */\n    // \"removeComments\": true,                           /* Disable emitting comments. */\n    // \"noEmit\": true,                                   /* Disable emitting files from a compilation. */\n    // \"importHelpers\": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */\n    // \"importsNotUsedAsValues\": \"remove\",               /* Specify emit/checking behavior for imports that are only used for types */\n    // \"downlevelIteration\": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */\n    // \"sourceRoot\": \"\",                                 /* Specify the root path for debuggers to find the reference source code. */\n    // \"mapRoot\": \"\",                                    /* Specify the location where debugger should locate map files instead of generated locations. */\n    // \"inlineSourceMap\": true,                          /* Include sourcemap files inside the emitted JavaScript. */\n    // \"inlineSources\": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */\n    // \"emitBOM\": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */\n    // \"newLine\": \"crlf\",                                /* Set the newline character for emitting files. */\n    // \"stripInternal\": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */\n    // \"noEmitHelpers\": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */\n    // \"noEmitOnError\": true,                            /* Disable emitting files if any type checking errors are reported. */\n    // \"preserveConstEnums\": true,                       /* Disable erasing `const enum` declarations in generated code. */\n    // \"declarationDir\": \"./\",                           /* Specify the output directory for generated declaration files. */\n    // \"preserveValueImports\": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */\n\n    /* Interop Constraints */\n    // \"isolatedModules\": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */\n    // \"allowSyntheticDefaultImports\": true,             /* Allow 'import x from y' when a module doesn't have a default export. */\n    \"esModuleInterop\": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */\n    // \"preserveSymlinks\": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */\n    \"forceConsistentCasingInFileNames\": true,            /* Ensure that casing is correct in imports. */\n\n    /* Type Checking */\n    \"strict\": true,                                      /* Enable all strict type-checking options. */\n    // \"noImplicitAny\": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */\n    // \"strictNullChecks\": true,                         /* When type checking, take into account `null` and `undefined`. */\n    // \"strictFunctionTypes\": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */\n    // \"strictBindCallApply\": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */\n    // \"strictPropertyInitialization\": true,             /* Check for class properties that are declared but not set in the constructor. */\n    // \"noImplicitThis\": true,                           /* Enable error reporting when `this` is given the type `any`. */\n    // \"useUnknownInCatchVariables\": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */\n    // \"alwaysStrict\": true,                             /* Ensure 'use strict' is always emitted. */\n    // \"noUnusedLocals\": true,                           /* Enable error reporting when a local variables aren't read. */\n    // \"noUnusedParameters\": true,                       /* Raise an error when a function parameter isn't read */\n    // \"exactOptionalPropertyTypes\": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */\n    // \"noImplicitReturns\": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */\n    // \"noFallthroughCasesInSwitch\": true,               /* Enable error reporting for fallthrough cases in switch statements. */\n    // \"noUncheckedIndexedAccess\": true,                 /* Include 'undefined' in index signature results */\n    // \"noImplicitOverride\": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */\n    // \"noPropertyAccessFromIndexSignature\": true,       /* Enforces using indexed accessors for keys declared using an indexed type */\n    // \"allowUnusedLabels\": true,                        /* Disable error reporting for unused labels. */\n    // \"allowUnreachableCode\": true,                     /* Disable error reporting for unreachable code. */\n\n    /* Completeness */\n    // \"skipDefaultLibCheck\": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */\n    \"skipLibCheck\": true                                 /* Skip type checking all .d.ts files. */\n  },\n  \"include\": [\"src/**/*.ts\"]\n}\n"
  },
  {
    "path": "ValidationByYupExample/.gitignore",
    "content": "/build\n/node_modules"
  },
  {
    "path": "ValidationByYupExample/.prettierrc",
    "content": "{\n    \"singleQuote\": true,\n    \"printWidth\": 200,\n    \"proseWrap\": \"always\",\n    \"tabWidth\": 4,\n    \"useTabs\": false,\n    \"trailingComma\": \"none\",\n    \"bracketSpacing\": true,\n    \"jsxBracketSameLine\": false,\n    \"semi\": true\n}\n"
  },
  {
    "path": "ValidationByYupExample/.vscode/settings.json",
    "content": "{\n    \"editor.defaultFormatter\": \"esbenp.prettier-vscode\",\n    \"editor.bracketPairColorization.enabled\": true,\n    \"editor.formatOnSave\": true,\n    \"editor.formatOnPaste\": true,\n    \"editor.wordWrap\": \"on\",\n    \"git.ignoreLimitWarning\": true\n}\n"
  },
  {
    "path": "ValidationByYupExample/README.md",
    "content": "# Restful API Data Validation & Control\n\n![N|Solid](https://lh3.googleusercontent.com/a-/AOh14GglnMoBPixoeH-IwaCWx7SpehtvYTPowns21fVO=s200-k-no-rp-mo)\n\nThis repository is a basic example of using various libraries to validate data that is passed to your api. Inside of the middleware folder, you can view each sample routes protection.\n\n## License\n\nMIT\n"
  },
  {
    "path": "ValidationByYupExample/package.json",
    "content": "{\n  \"name\": \"joi-example\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"src/server.ts\",\n  \"scripts\": {\n    \"build\": \"rm -rf build && prettier --write source/ && tsc\"\n  },\n  \"author\": \"\",\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"express\": \"^4.17.2\",\n    \"joi\": \"^17.5.0\",\n    \"yup\": \"^0.32.11\"\n  },\n  \"devDependencies\": {\n    \"@types/express\": \"^4.17.13\",\n    \"typescript\": \"^4.5.4\"\n  }\n}\n"
  },
  {
    "path": "ValidationByYupExample/src/controllers/yup.ts",
    "content": "import { NextFunction, Request, Response } from 'express';\nimport { IYupData } from '../interfaces/yup';\n\nconst yupSampleRoute = (req: Request, res: Response, next: NextFunction) => {\n    return res.status(200).json({\n        locals: res.locals.data as IYupData,\n        body: req.body\n    });\n};\n\nexport default { yupSampleRoute };\n"
  },
  {
    "path": "ValidationByYupExample/src/interfaces/yup.ts",
    "content": "export interface IYupData {\n    name: string;\n    age: number;\n    email?: string | undefined;\n    website?: string | null | undefined;\n    createdOn: Date;\n}\n"
  },
  {
    "path": "ValidationByYupExample/src/middleware/yup.ts",
    "content": "import { object, string, number, date, AnyObjectSchema } from 'yup';\nimport { NextFunction, Request, Response } from 'express';\n\nexport const ValidateYup = (schema: AnyObjectSchema) => {\n    return async (req: Request, res: Response, next: NextFunction) => {\n        try {\n            const data = await schema.validate(req.body);\n\n            console.log(data);\n\n            res.locals.data = data;\n\n            next();\n        } catch (error) {\n            console.error(error);\n\n            return res.status(422).json({ error });\n        }\n    };\n};\n\nexport const Schemas = {\n    data: object().shape({\n        name: string().required(),\n        age: number().required().positive().integer(),\n        email: string().email(),\n        website: string().url(),\n        createdOn: date().default(() => new Date())\n    })\n};\n"
  },
  {
    "path": "ValidationByYupExample/src/routes/yup.ts",
    "content": "import express from 'express';\nimport controller from '../controllers/yup';\nimport { Schemas, ValidateYup } from '../middleware/yup';\n\nconst router = express.Router();\n\nrouter.post('/', ValidateYup(Schemas.data), controller.yupSampleRoute);\n\nexport = router;\n"
  },
  {
    "path": "ValidationByYupExample/src/server.ts",
    "content": "import http from 'http';\nimport express from 'express';\nimport yupRoutes from './routes/yup';\n\nconst router = express();\n\n/** Log the request */\nrouter.use((req, res, next) => {\n    /** Log the req */\n    console.info(`METHOD: [${req.method}] - URL: [${req.url}] - IP: [${req.socket.remoteAddress}]`);\n\n    res.on('finish', () => {\n        /** Log the res */\n        console.info(`METHOD: [${req.method}] - URL: [${req.url}] - STATUS: [${res.statusCode}] - IP: [${req.socket.remoteAddress}]`);\n    });\n\n    next();\n});\n\nrouter.use(express.urlencoded({ extended: true }));\nrouter.use(express.json());\n\n/** Rules of our API */\nrouter.use((req, res, next) => {\n    res.header('Access-Control-Allow-Origin', '*');\n    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');\n\n    if (req.method == 'OPTIONS') {\n        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');\n        return res.status(200).json({});\n    }\n\n    next();\n});\n\n/** Routes */\nrouter.use('/yup', yupRoutes);\n\n/** Error handling */\nrouter.use((req, res, next) => {\n    const error = new Error('Not found');\n\n    return res.status(404).json({\n        message: error.message\n    });\n});\n\nconst httpServer = http.createServer(router);\nhttpServer.listen(1337, () => console.info('Server is running on port 1337 ...'));\n"
  },
  {
    "path": "ValidationByYupExample/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    /* Visit https://aka.ms/tsconfig.json to read more about this file */\n\n    /* Projects */\n    // \"incremental\": true,                              /* Enable incremental compilation */\n    // \"composite\": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */\n    // \"tsBuildInfoFile\": \"./\",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */\n    // \"disableSourceOfProjectReferenceRedirect\": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */\n    // \"disableSolutionSearching\": true,                 /* Opt a project out of multi-project reference checking when editing. */\n    // \"disableReferencedProjectLoad\": true,             /* Reduce the number of projects loaded automatically by TypeScript. */\n\n    /* Language and Environment */\n    \"target\": \"es2016\",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */\n    // \"lib\": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */\n    // \"jsx\": \"preserve\",                                /* Specify what JSX code is generated. */\n    // \"experimentalDecorators\": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */\n    // \"emitDecoratorMetadata\": true,                    /* Emit design-type metadata for decorated declarations in source files. */\n    // \"jsxFactory\": \"\",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */\n    // \"jsxFragmentFactory\": \"\",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */\n    // \"jsxImportSource\": \"\",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */\n    // \"reactNamespace\": \"\",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */\n    // \"noLib\": true,                                    /* Disable including any library files, including the default lib.d.ts. */\n    // \"useDefineForClassFields\": true,                  /* Emit ECMAScript-standard-compliant class fields. */\n\n    /* Modules */\n    \"module\": \"commonjs\",                                /* Specify what module code is generated. */\n    // \"rootDir\": \"./\",                                  /* Specify the root folder within your source files. */\n    // \"moduleResolution\": \"node\",                       /* Specify how TypeScript looks up a file from a given module specifier. */\n    // \"baseUrl\": \"./\",                                  /* Specify the base directory to resolve non-relative module names. */\n    // \"paths\": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */\n    // \"rootDirs\": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */\n    // \"typeRoots\": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */\n    // \"types\": [],                                      /* Specify type package names to be included without being referenced in a source file. */\n    // \"allowUmdGlobalAccess\": true,                     /* Allow accessing UMD globals from modules. */\n    // \"resolveJsonModule\": true,                        /* Enable importing .json files */\n    // \"noResolve\": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */\n\n    /* JavaScript Support */\n    // \"allowJs\": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */\n    // \"checkJs\": true,                                  /* Enable error reporting in type-checked JavaScript files. */\n    // \"maxNodeModuleJsDepth\": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */\n\n    /* Emit */\n    // \"declaration\": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */\n    // \"declarationMap\": true,                           /* Create sourcemaps for d.ts files. */\n    // \"emitDeclarationOnly\": true,                      /* Only output d.ts files and not JavaScript files. */\n    // \"sourceMap\": true,                                /* Create source map files for emitted JavaScript files. */\n    // \"outFile\": \"./\",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */\n    \"outDir\": \"./build\",                                   /* Specify an output folder for all emitted files. */\n    // \"removeComments\": true,                           /* Disable emitting comments. */\n    // \"noEmit\": true,                                   /* Disable emitting files from a compilation. */\n    // \"importHelpers\": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */\n    // \"importsNotUsedAsValues\": \"remove\",               /* Specify emit/checking behavior for imports that are only used for types */\n    // \"downlevelIteration\": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */\n    // \"sourceRoot\": \"\",                                 /* Specify the root path for debuggers to find the reference source code. */\n    // \"mapRoot\": \"\",                                    /* Specify the location where debugger should locate map files instead of generated locations. */\n    // \"inlineSourceMap\": true,                          /* Include sourcemap files inside the emitted JavaScript. */\n    // \"inlineSources\": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */\n    // \"emitBOM\": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */\n    // \"newLine\": \"crlf\",                                /* Set the newline character for emitting files. */\n    // \"stripInternal\": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */\n    // \"noEmitHelpers\": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */\n    // \"noEmitOnError\": true,                            /* Disable emitting files if any type checking errors are reported. */\n    // \"preserveConstEnums\": true,                       /* Disable erasing `const enum` declarations in generated code. */\n    // \"declarationDir\": \"./\",                           /* Specify the output directory for generated declaration files. */\n    // \"preserveValueImports\": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */\n\n    /* Interop Constraints */\n    // \"isolatedModules\": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */\n    // \"allowSyntheticDefaultImports\": true,             /* Allow 'import x from y' when a module doesn't have a default export. */\n    \"esModuleInterop\": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */\n    // \"preserveSymlinks\": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */\n    \"forceConsistentCasingInFileNames\": true,            /* Ensure that casing is correct in imports. */\n\n    /* Type Checking */\n    \"strict\": true,                                      /* Enable all strict type-checking options. */\n    // \"noImplicitAny\": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */\n    // \"strictNullChecks\": true,                         /* When type checking, take into account `null` and `undefined`. */\n    // \"strictFunctionTypes\": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */\n    // \"strictBindCallApply\": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */\n    // \"strictPropertyInitialization\": true,             /* Check for class properties that are declared but not set in the constructor. */\n    // \"noImplicitThis\": true,                           /* Enable error reporting when `this` is given the type `any`. */\n    // \"useUnknownInCatchVariables\": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */\n    // \"alwaysStrict\": true,                             /* Ensure 'use strict' is always emitted. */\n    // \"noUnusedLocals\": true,                           /* Enable error reporting when a local variables aren't read. */\n    // \"noUnusedParameters\": true,                       /* Raise an error when a function parameter isn't read */\n    // \"exactOptionalPropertyTypes\": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */\n    // \"noImplicitReturns\": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */\n    // \"noFallthroughCasesInSwitch\": true,               /* Enable error reporting for fallthrough cases in switch statements. */\n    // \"noUncheckedIndexedAccess\": true,                 /* Include 'undefined' in index signature results */\n    // \"noImplicitOverride\": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */\n    // \"noPropertyAccessFromIndexSignature\": true,       /* Enforces using indexed accessors for keys declared using an indexed type */\n    // \"allowUnusedLabels\": true,                        /* Disable error reporting for unused labels. */\n    // \"allowUnreachableCode\": true,                     /* Disable error reporting for unreachable code. */\n\n    /* Completeness */\n    // \"skipDefaultLibCheck\": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */\n    \"skipLibCheck\": true                                 /* Skip type checking all .d.ts files. */\n  },\n  \"include\": [\"src/**/*.ts\"]\n}\n"
  },
  {
    "path": "readme.md",
    "content": "# NodeJS Typescript Quickstart Projects\n\n![N|Solid](https://lh3.googleusercontent.com/a-/AOh14GglnMoBPixoeH-IwaCWx7SpehtvYTPowns21fVO=s200-k-no-rp-mo)\n\n[![GitHub stars](https://img.shields.io/github/stars/joeythelantern/Typescript-Quickstart-Projects.svg)](https://github.com/joeythelantern/Typescript-Quickstart-Projects/stargazers)\n[![GitHub license](https://img.shields.io/github/license/joeythelantern/Typescript-Quickstart-Projects.svg)](https://github.com/joeythelantern/Typescript-Quickstart-Projects/blob/master/LICENCE)\n[![GitHub forks](https://img.shields.io/github/forks/joeythelantern/Typescript-Quickstart-Projects.svg)](https://github.com/joeythelantern/Typescript-Quickstart-Projects/network)\n[![Youtube_Channel_Views](https://img.shields.io/youtube/channel/views/UCmG1UbEI0iFE1tAw2SyvvXg?label=Channel%20Views&style=social.svg)](https://img.shields.io/youtube/channel/views/UCmG1UbEI0iFE1tAw2SyvvXg?label=Channel%20Views&style=social)\n\nHey everyone! This repository is a 3 in 1 boilerplate that gives you some basic examples of creating a RESTful API in NodeJS, Express, Typescript and an optional database interaction with either MySQL or Mongo.  This repository contains 3 folders.  Here is a breif description of each, along with a link to a youtube video that will help you code it out yourself:\n\n  - typescript-express-nodejs-quickstart\n    - Stats: ![N|Solid](https://img.shields.io/youtube/views/vyz47fUXcxU?style=social.svg) ![N|Solid](https://img.shields.io/youtube/likes/vyz47fUXcxU?style=social.svg)\n    - A basic boilerplate wwith a sample route and controller.\n    - [https://youtu.be/vyz47fUXcxU](https://youtu.be/vyz47fUXcxU)\n  - typescript-mongoose-quickstart\n    - Stats: ![N|Solid](https://img.shields.io/youtube/views/lNqaQ0wEeAo?style=social.svg) ![N|Solid](https://img.shields.io/youtube/likes/lNqaQ0wEeAo?style=social.svg)\n    - The same boilerplate with a sample MongoDB connection.\n    - [https://youtu.be/lNqaQ0wEeAo](https://youtu.be/lNqaQ0wEeAo)\n  - typescript-mysql-quickstart\n    - Stats: ![N|Solid](https://img.shields.io/youtube/views/eTRSl1As83A?style=social.svg) ![N|Solid](https://img.shields.io/youtube/likes/eTRSl1As83A?style=social.svg)\n    - Similar to the Mongo project, but with a custom mysql promise adapter.\n    - [https://youtu.be/eTRSl1As83A](https://youtu.be/eTRSl1As83A)\n  - ValidationByJoiExample\n    - Stats: ![N|Solid](https://img.shields.io/youtube/views/J5u9kXnPn8U?style=social.svg) ![N|Solid](https://img.shields.io/youtube/likes/J5u9kXnPn8U?style=social.svg)\n    - Protect your API and validate your data using JOI. \n    - [https://youtu.be/J5u9kXnPn8U](https://youtu.be/J5u9kXnPn8U)\n  - ValidationByYupExample\n    - Stats: ![N|Solid](https://img.shields.io/youtube/views/JgZ3RWcI3pk?style=social.svg) ![N|Solid](https://img.shields.io/youtube/likes/JgZ3RWcI3pk?style=social.svg)\n    - Protect your API and validate your data using YUP. \n    - [https://youtu.be/J5u9kXnPn8U](https://youtu.be/JgZ3RWcI3pk)\n\nPeriodic updates may happen to this repo to make small bug fixes or improvements.  Feel free to fork this repository and code away.\n\n# Updates / Bug Fixes\n* 01/23/2021 - Adding MIT Licesnse \n* 01/16/2020 - Fixing logging & logging the end of the request properly\n\n### Installation\n\nInstall the dependencies and start the server.  When you clonse the respository, cd into it and cd into one of the directories to start.  Whichever one you pick is where you will run the following commands below.  <project_directory> is the directory you've chosen.\n\n```sh\n$ cd <project_directory>\n$ npm install\n```\n\nLicense\n----\nMIT\n"
  },
  {
    "path": "typescript-express-nodejs-quickstart/.gitignore",
    "content": "node_modules/**/*\nbuild/**/*\ncerts/**/*\n\n*.jks\n*.p8\n*.p12\n*.key\n*.mobileprovision\n*.orig.*\n\npackage-lock.json"
  },
  {
    "path": "typescript-express-nodejs-quickstart/.prettierrc",
    "content": "{\n    \"singleQuote\": true,\n    \"printWidth\": 200,\n    \"proseWrap\": \"always\",\n    \"tabWidth\": 4,\n    \"useTabs\": false,\n    \"trailingComma\": \"none\",\n    \"bracketSpacing\": true,\n    \"jsxBracketSameLine\": false,\n    \"semi\": true\n}"
  },
  {
    "path": "typescript-express-nodejs-quickstart/.vscode/settings.json",
    "content": "{\n  \"editor.defaultFormatter\": \"esbenp.prettier-vscode\",\n  \"editor.bracketPairColorization.enabled\": true,\n  \"editor.formatOnSave\": true,\n  \"editor.formatOnPaste\": true,\n  \"editor.wordWrap\": \"on\"\n}\n"
  },
  {
    "path": "typescript-express-nodejs-quickstart/package.json",
    "content": "{\n  \"name\": \"api\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"source/server.ts\",\n  \"scripts\": {\n    \"build\": \"rm -rf build && prettier --write source/ && tsc\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"body-parser\": \"^1.19.0\",\n    \"dotenv\": \"^8.2.0\",\n    \"express\": \"^4.17.1\"\n  },\n  \"devDependencies\": {\n    \"@types/body-parser\": \"^1.19.0\",\n    \"@types/dotenv\": \"^8.2.0\",\n    \"@types/express\": \"^4.17.8\"\n  }\n}\n"
  },
  {
    "path": "typescript-express-nodejs-quickstart/source/config/config.ts",
    "content": "import dotenv from 'dotenv';\n\ndotenv.config();\n\nconst SERVER_HOSTNAME = process.env.SERVER_HOSTNAME || 'localhost';\nconst SERVER_PORT = process.env.SERVER_PORT || 1337;\n\nconst SERVER = {\n    hostname: SERVER_HOSTNAME,\n    port: SERVER_PORT\n};\n\nconst config = {\n    server: SERVER\n};\n\nexport default config;\n"
  },
  {
    "path": "typescript-express-nodejs-quickstart/source/config/logging.ts",
    "content": "const info = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.info(`[${getTimeStamp()}] [INFO] [${namespace}] ${message}`, object);\n    } else {\n        console.info(`[${getTimeStamp()}] [INFO] [${namespace}] ${message}`);\n    }\n};\n\nconst warn = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.warn(`[${getTimeStamp()}] [WARN] [${namespace}] ${message}`, object);\n    } else {\n        console.warn(`[${getTimeStamp()}] [WARN] [${namespace}] ${message}`);\n    }\n};\n\nconst error = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.error(`[${getTimeStamp()}] [ERROR] [${namespace}] ${message}`, object);\n    } else {\n        console.error(`[${getTimeStamp()}] [ERROR] [${namespace}] ${message}`);\n    }\n};\n\nconst debug = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.debug(`[${getTimeStamp()}] [DEBUG] [${namespace}] ${message}`, object);\n    } else {\n        console.debug(`[${getTimeStamp()}] [DEBUG] [${namespace}] ${message}`);\n    }\n};\n\nconst getTimeStamp = (): string => {\n    return new Date().toISOString();\n};\n\nexport default {\n    info,\n    warn,\n    error,\n    debug\n};\n"
  },
  {
    "path": "typescript-express-nodejs-quickstart/source/controllers/sample.ts",
    "content": "import { NextFunction, Request, Response } from 'express';\n\nconst serverHealthCheck = (req: Request, res: Response, next: NextFunction) => {\n    return res.status(200).json({\n        message: 'pong'\n    });\n};\n\nexport default { serverHealthCheck };\n"
  },
  {
    "path": "typescript-express-nodejs-quickstart/source/routes/sample.ts",
    "content": "import express from 'express';\nimport controller from '../controllers/sample';\n\nconst router = express.Router();\n\nrouter.get('/ping', controller.serverHealthCheck);\n\nexport = router;\n"
  },
  {
    "path": "typescript-express-nodejs-quickstart/source/server.ts",
    "content": "import http from 'http';\nimport bodyParser from 'body-parser';\nimport express from 'express';\nimport logging from './config/logging';\nimport config from './config/config';\nimport sampleRoutes from './routes/sample';\n\nconst NAMESPACE = 'Server';\nconst router = express();\n\n/** Log the request */\nrouter.use((req, res, next) => {\n    /** Log the req */\n    logging.info(NAMESPACE, `METHOD: [${req.method}] - URL: [${req.url}] - IP: [${req.socket.remoteAddress}]`);\n\n    res.on('finish', () => {\n        /** Log the res */\n        logging.info(NAMESPACE, `METHOD: [${req.method}] - URL: [${req.url}] - STATUS: [${res.statusCode}] - IP: [${req.socket.remoteAddress}]`);\n    })\n    \n    next();\n});\n\n/** Parse the body of the request */\nrouter.use(bodyParser.urlencoded({ extended: true }));\nrouter.use(bodyParser.json());\n\n/** Rules of our API */\nrouter.use((req, res, next) => {\n    res.header('Access-Control-Allow-Origin', '*');\n    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');\n\n    if (req.method == 'OPTIONS') {\n        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');\n        return res.status(200).json({});\n    }\n\n    next();\n});\n\n/** Routes go here */\nrouter.use('/api/sample', sampleRoutes);\n\n/** Error handling */\nrouter.use((req, res, next) => {\n    const error = new Error('Not found');\n\n    res.status(404).json({\n        message: error.message\n    });\n});\n\nconst httpServer = http.createServer(router);\n\nhttpServer.listen(config.server.port, () => logging.info(NAMESPACE, `Server is running ${config.server.hostname}:${config.server.port}`));\n"
  },
  {
    "path": "typescript-express-nodejs-quickstart/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    /* Visit https://aka.ms/tsconfig.json to read more about this file */\n\n    /* Basic Options */\n    // \"incremental\": true,                   /* Enable incremental compilation */\n    \"target\": \"es5\",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */\n    \"module\": \"commonjs\",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */\n    // \"lib\": [],                             /* Specify library files to be included in the compilation. */\n    // \"allowJs\": true,                       /* Allow javascript files to be compiled. */\n    // \"checkJs\": true,                       /* Report errors in .js files. */\n    // \"jsx\": \"preserve\",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */\n    // \"declaration\": true,                   /* Generates corresponding '.d.ts' file. */\n    // \"declarationMap\": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */\n    // \"sourceMap\": true,                     /* Generates corresponding '.map' file. */\n    // \"outFile\": \"./\",                       /* Concatenate and emit output to single file. */\n    \"outDir\": \"./build\",                        /* Redirect output structure to the directory. */\n    // \"rootDir\": \"./\",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */\n    // \"composite\": true,                     /* Enable project compilation */\n    // \"tsBuildInfoFile\": \"./\",               /* Specify file to store incremental compilation information */\n    // \"removeComments\": true,                /* Do not emit comments to output. */\n    // \"noEmit\": true,                        /* Do not emit outputs. */\n    // \"importHelpers\": true,                 /* Import emit helpers from 'tslib'. */\n    // \"downlevelIteration\": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */\n    // \"isolatedModules\": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */\n\n    /* Strict Type-Checking Options */\n    \"strict\": true,                           /* Enable all strict type-checking options. */\n    // \"noImplicitAny\": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */\n    // \"strictNullChecks\": true,              /* Enable strict null checks. */\n    // \"strictFunctionTypes\": true,           /* Enable strict checking of function types. */\n    // \"strictBindCallApply\": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */\n    // \"strictPropertyInitialization\": true,  /* Enable strict checking of property initialization in classes. */\n    // \"noImplicitThis\": true,                /* Raise error on 'this' expressions with an implied 'any' type. */\n    // \"alwaysStrict\": true,                  /* Parse in strict mode and emit \"use strict\" for each source file. */\n\n    /* Additional Checks */\n    // \"noUnusedLocals\": true,                /* Report errors on unused locals. */\n    // \"noUnusedParameters\": true,            /* Report errors on unused parameters. */\n    // \"noImplicitReturns\": true,             /* Report error when not all code paths in function return a value. */\n    // \"noFallthroughCasesInSwitch\": true,    /* Report errors for fallthrough cases in switch statement. */\n\n    /* Module Resolution Options */\n    // \"moduleResolution\": \"node\",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */\n    // \"baseUrl\": \"./\",                       /* Base directory to resolve non-absolute module names. */\n    // \"paths\": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */\n    // \"rootDirs\": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */\n    // \"typeRoots\": [],                       /* List of folders to include type definitions from. */\n    // \"types\": [],                           /* Type declaration files to be included in compilation. */\n    // \"allowSyntheticDefaultImports\": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */\n    \"esModuleInterop\": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */\n    // \"preserveSymlinks\": true,              /* Do not resolve the real path of symlinks. */\n    // \"allowUmdGlobalAccess\": true,          /* Allow accessing UMD globals from modules. */\n\n    /* Source Map Options */\n    // \"sourceRoot\": \"\",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */\n    // \"mapRoot\": \"\",                         /* Specify the location where debugger should locate map files instead of generated locations. */\n    // \"inlineSourceMap\": true,               /* Emit a single file with source maps instead of having a separate file. */\n    // \"inlineSources\": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */\n\n    /* Experimental Options */\n    // \"experimentalDecorators\": true,        /* Enables experimental support for ES7 decorators. */\n    // \"emitDecoratorMetadata\": true,         /* Enables experimental support for emitting type metadata for decorators. */\n\n    /* Advanced Options */\n    \"skipLibCheck\": true,                     /* Skip type checking of declaration files. */\n    \"forceConsistentCasingInFileNames\": true  /* Disallow inconsistently-cased references to the same file. */\n  }\n}\n"
  },
  {
    "path": "typescript-mongoose-quickstart/.gitignore",
    "content": "node_modules/**/*\nbuild/**/*\ncerts/**/*\n\n*.jks\n*.p8\n*.p12\n*.key\n*.mobileprovision\n*.orig.*\n\npackage-lock.json"
  },
  {
    "path": "typescript-mongoose-quickstart/.prettierrc",
    "content": "{\n    \"singleQuote\": true,\n    \"printWidth\": 200,\n    \"proseWrap\": \"always\",\n    \"tabWidth\": 4,\n    \"useTabs\": false,\n    \"trailingComma\": \"none\",\n    \"bracketSpacing\": true,\n    \"jsxBracketSameLine\": false,\n    \"semi\": true\n}"
  },
  {
    "path": "typescript-mongoose-quickstart/.vscode/settings.json",
    "content": "{\n  \"editor.defaultFormatter\": \"esbenp.prettier-vscode\",\n  \"editor.bracketPairColorization.enabled\": true,\n  \"editor.formatOnSave\": true,\n  \"editor.formatOnPaste\": true,\n  \"editor.wordWrap\": \"on\"\n}\n"
  },
  {
    "path": "typescript-mongoose-quickstart/package.json",
    "content": "{\n  \"name\": \"api\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"source/server.ts\",\n  \"scripts\": {\n    \"build\": \"rm -rf build && prettier --write source/ && tsc\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"body-parser\": \"^1.19.0\",\n    \"dotenv\": \"^8.2.0\",\n    \"express\": \"^4.17.1\",\n    \"mongoose\": \"^5.10.15\"\n  },\n  \"devDependencies\": {\n    \"@types/body-parser\": \"^1.19.0\",\n    \"@types/dotenv\": \"^8.2.0\",\n    \"@types/express\": \"^4.17.8\",\n    \"@types/mongoose\": \"^5.10.1\"\n  }\n}\n"
  },
  {
    "path": "typescript-mongoose-quickstart/source/config/config.ts",
    "content": "import dotenv from 'dotenv';\n\ndotenv.config();\n\nconst MONGO_OPTIONS = {\n    useUnifiedTopology: true,\n    useNewUrlParser: true,\n    socketTimeoutMS: 30000,\n    keepAlive: true,\n    poolSize: 50,\n    autoIndex: false,\n    retryWrites: false\n};\n\nconst MONGO_USERNAME = process.env.MONGO_USERNAME || 'superuser';\nconst MONGO_PASSWORD = process.env.MONGO_USERNAME || 'supersecretpassword1';\nconst MONGO_HOST = process.env.MONGO_URL || `ds343895.mlab.com:43895/mongobongo`;\n\nconst MONGO = {\n    host: MONGO_HOST,\n    password: MONGO_PASSWORD,\n    username: MONGO_USERNAME,\n    options: MONGO_OPTIONS,\n    url: `mongodb://${MONGO_USERNAME}:${MONGO_PASSWORD}@${MONGO_HOST}`\n};\n\nconst SERVER_HOSTNAME = process.env.SERVER_HOSTNAME || 'localhost';\nconst SERVER_PORT = process.env.SERVER_PORT || 1337;\n\nconst SERVER = {\n    hostname: SERVER_HOSTNAME,\n    port: SERVER_PORT\n};\n\nconst config = {\n    mongo: MONGO,\n    server: SERVER\n};\n\nexport default config;\n"
  },
  {
    "path": "typescript-mongoose-quickstart/source/config/logging.ts",
    "content": "const info = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.info(`[${getTimeStamp()}] [INFO] [${namespace}] ${message}`, object);\n    } else {\n        console.info(`[${getTimeStamp()}] [INFO] [${namespace}] ${message}`);\n    }\n};\n\nconst warn = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.warn(`[${getTimeStamp()}] [WARN] [${namespace}] ${message}`, object);\n    } else {\n        console.warn(`[${getTimeStamp()}] [WARN] [${namespace}] ${message}`);\n    }\n};\n\nconst error = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.error(`[${getTimeStamp()}] [ERROR] [${namespace}] ${message}`, object);\n    } else {\n        console.error(`[${getTimeStamp()}] [ERROR] [${namespace}] ${message}`);\n    }\n};\n\nconst debug = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.debug(`[${getTimeStamp()}] [DEBUG] [${namespace}] ${message}`, object);\n    } else {\n        console.debug(`[${getTimeStamp()}] [DEBUG] [${namespace}] ${message}`);\n    }\n};\n\nconst getTimeStamp = (): string => {\n    return new Date().toISOString();\n};\n\nexport default {\n    info,\n    warn,\n    error,\n    debug\n};\n"
  },
  {
    "path": "typescript-mongoose-quickstart/source/controllers/book.ts",
    "content": "import { NextFunction, Request, Response } from 'express';\nimport mongoose from 'mongoose';\nimport Book from '../models/book';\n\nconst createBook = (req: Request, res: Response, next: NextFunction) => {\n    let { author, title } = req.body;\n\n    const book = new Book({\n        _id: new mongoose.Types.ObjectId(),\n        author,\n        title\n    });\n\n    return book\n        .save()\n        .then((result) => {\n            return res.status(201).json({\n                book: result\n            });\n        })\n        .catch((error) => {\n            return res.status(500).json({\n                message: error.message,\n                error\n            });\n        });\n};\n\nconst getAllBooks = (req: Request, res: Response, next: NextFunction) => {\n    Book.find()\n        .exec()\n        .then((books) => {\n            return res.status(200).json({\n                books: books,\n                count: books.length\n            });\n        })\n        .catch((error) => {\n            return res.status(500).json({\n                message: error.message,\n                error\n            });\n        });\n};\n\nexport default { createBook, getAllBooks };\n"
  },
  {
    "path": "typescript-mongoose-quickstart/source/interfaces/book.ts",
    "content": "import { Document } from 'mongoose';\n\nexport default interface IBook extends Document {\n    title: string;\n    author: string;\n}\n"
  },
  {
    "path": "typescript-mongoose-quickstart/source/models/book.ts",
    "content": "import mongoose, { Schema } from 'mongoose';\nimport logging from '../config/logging';\nimport IBook from '../interfaces/book';\n\nconst BookSchema: Schema = new Schema(\n    {\n        title: { type: String, required: true },\n        author: { type: String, required: true }\n    },\n    {\n        timestamps: true\n    }\n);\n\nBookSchema.post<IBook>('save', function () {\n    logging.info('Mongo', 'Checkout the book we just saved: ', this);\n});\n\nexport default mongoose.model<IBook>('Book', BookSchema);\n"
  },
  {
    "path": "typescript-mongoose-quickstart/source/routes/book.ts",
    "content": "import express from 'express';\nimport controller from '../controllers/book';\n\nconst router = express.Router();\n\nrouter.post('/create/book', controller.createBook);\nrouter.get('/get/books', controller.getAllBooks);\n\nexport = router;\n"
  },
  {
    "path": "typescript-mongoose-quickstart/source/server.ts",
    "content": "import http from 'http';\nimport bodyParser from 'body-parser';\nimport express from 'express';\nimport logging from './config/logging';\nimport config from './config/config';\nimport bookRoutes from './routes/book';\nimport mongoose from 'mongoose';\n\nconst NAMESPACE = 'Server';\nconst router = express();\n\n/** Connect to Mongo */\nmongoose\n    .connect(config.mongo.url, config.mongo.options)\n    .then((result) => {\n        logging.info(NAMESPACE, 'Mongo Connected');\n    })\n    .catch((error) => {\n        logging.error(NAMESPACE, error.message, error);\n    });\n\n/** Log the request */\nrouter.use((req, res, next) => {\n    /** Log the req */\n    logging.info(NAMESPACE, `METHOD: [${req.method}] - URL: [${req.url}] - IP: [${req.socket.remoteAddress}]`);\n\n    res.on('finish', () => {\n        /** Log the res */\n        logging.info(NAMESPACE, `METHOD: [${req.method}] - URL: [${req.url}] - STATUS: [${res.statusCode}] - IP: [${req.socket.remoteAddress}]`);\n    })\n    \n    next();\n});\n\n/** Parse the body of the request */\nrouter.use(bodyParser.urlencoded({ extended: true }));\nrouter.use(bodyParser.json());\n\n/** Rules of our API */\nrouter.use((req, res, next) => {\n    res.header('Access-Control-Allow-Origin', '*');\n    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');\n\n    if (req.method == 'OPTIONS') {\n        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');\n        return res.status(200).json({});\n    }\n\n    next();\n});\n\n/** Routes go here */\nrouter.use('/api/books', bookRoutes);\n\n/** Error handling */\nrouter.use((req, res, next) => {\n    const error = new Error('Not found');\n\n    res.status(404).json({\n        message: error.message\n    });\n});\n\nconst httpServer = http.createServer(router);\n\nhttpServer.listen(config.server.port, () => logging.info(NAMESPACE, `Server is running ${config.server.hostname}:${config.server.port}`));\n"
  },
  {
    "path": "typescript-mongoose-quickstart/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    /* Visit https://aka.ms/tsconfig.json to read more about this file */\n\n    /* Basic Options */\n    // \"incremental\": true,                   /* Enable incremental compilation */\n    \"target\": \"es5\",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */\n    \"module\": \"commonjs\",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */\n    // \"lib\": [],                             /* Specify library files to be included in the compilation. */\n    // \"allowJs\": true,                       /* Allow javascript files to be compiled. */\n    // \"checkJs\": true,                       /* Report errors in .js files. */\n    // \"jsx\": \"preserve\",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */\n    // \"declaration\": true,                   /* Generates corresponding '.d.ts' file. */\n    // \"declarationMap\": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */\n    // \"sourceMap\": true,                     /* Generates corresponding '.map' file. */\n    // \"outFile\": \"./\",                       /* Concatenate and emit output to single file. */\n    \"outDir\": \"./build\",                        /* Redirect output structure to the directory. */\n    // \"rootDir\": \"./\",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */\n    // \"composite\": true,                     /* Enable project compilation */\n    // \"tsBuildInfoFile\": \"./\",               /* Specify file to store incremental compilation information */\n    // \"removeComments\": true,                /* Do not emit comments to output. */\n    // \"noEmit\": true,                        /* Do not emit outputs. */\n    // \"importHelpers\": true,                 /* Import emit helpers from 'tslib'. */\n    // \"downlevelIteration\": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */\n    // \"isolatedModules\": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */\n\n    /* Strict Type-Checking Options */\n    \"strict\": true,                           /* Enable all strict type-checking options. */\n    // \"noImplicitAny\": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */\n    // \"strictNullChecks\": true,              /* Enable strict null checks. */\n    // \"strictFunctionTypes\": true,           /* Enable strict checking of function types. */\n    // \"strictBindCallApply\": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */\n    // \"strictPropertyInitialization\": true,  /* Enable strict checking of property initialization in classes. */\n    // \"noImplicitThis\": true,                /* Raise error on 'this' expressions with an implied 'any' type. */\n    // \"alwaysStrict\": true,                  /* Parse in strict mode and emit \"use strict\" for each source file. */\n\n    /* Additional Checks */\n    // \"noUnusedLocals\": true,                /* Report errors on unused locals. */\n    // \"noUnusedParameters\": true,            /* Report errors on unused parameters. */\n    // \"noImplicitReturns\": true,             /* Report error when not all code paths in function return a value. */\n    // \"noFallthroughCasesInSwitch\": true,    /* Report errors for fallthrough cases in switch statement. */\n\n    /* Module Resolution Options */\n    // \"moduleResolution\": \"node\",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */\n    // \"baseUrl\": \"./\",                       /* Base directory to resolve non-absolute module names. */\n    // \"paths\": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */\n    // \"rootDirs\": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */\n    // \"typeRoots\": [],                       /* List of folders to include type definitions from. */\n    // \"types\": [],                           /* Type declaration files to be included in compilation. */\n    // \"allowSyntheticDefaultImports\": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */\n    \"esModuleInterop\": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */\n    // \"preserveSymlinks\": true,              /* Do not resolve the real path of symlinks. */\n    // \"allowUmdGlobalAccess\": true,          /* Allow accessing UMD globals from modules. */\n\n    /* Source Map Options */\n    // \"sourceRoot\": \"\",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */\n    // \"mapRoot\": \"\",                         /* Specify the location where debugger should locate map files instead of generated locations. */\n    // \"inlineSourceMap\": true,               /* Emit a single file with source maps instead of having a separate file. */\n    // \"inlineSources\": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */\n\n    /* Experimental Options */\n    // \"experimentalDecorators\": true,        /* Enables experimental support for ES7 decorators. */\n    // \"emitDecoratorMetadata\": true,         /* Enables experimental support for emitting type metadata for decorators. */\n\n    /* Advanced Options */\n    \"skipLibCheck\": true,                     /* Skip type checking of declaration files. */\n    \"forceConsistentCasingInFileNames\": true  /* Disallow inconsistently-cased references to the same file. */\n  }\n}\n"
  },
  {
    "path": "typescript-mysql-quickstart/.gitignore",
    "content": "node_modules/**/*\nbuild/**/*\ncerts/**/*\n\n*.jks\n*.p8\n*.p12\n*.key\n*.mobileprovision\n*.orig.*\n\npackage-lock.json"
  },
  {
    "path": "typescript-mysql-quickstart/.prettierrc",
    "content": "{\n    \"singleQuote\": true,\n    \"printWidth\": 200,\n    \"proseWrap\": \"always\",\n    \"tabWidth\": 4,\n    \"useTabs\": false,\n    \"trailingComma\": \"none\",\n    \"bracketSpacing\": true,\n    \"jsxBracketSameLine\": false,\n    \"semi\": true\n}"
  },
  {
    "path": "typescript-mysql-quickstart/.vscode/settings.json",
    "content": "{\n  \"editor.defaultFormatter\": \"esbenp.prettier-vscode\",\n  \"editor.bracketPairColorization.enabled\": true,\n  \"editor.formatOnSave\": true,\n  \"editor.formatOnPaste\": true,\n  \"editor.wordWrap\": \"on\"\n}\n"
  },
  {
    "path": "typescript-mysql-quickstart/package.json",
    "content": "{\n  \"name\": \"api\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"source/server.ts\",\n  \"scripts\": {\n    \"build\": \"rm -rf build && prettier --write source/ && tsc\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"body-parser\": \"^1.19.0\",\n    \"dotenv\": \"^8.2.0\",\n    \"express\": \"^4.17.1\",\n    \"mysql\": \"^2.18.1\"\n  },\n  \"devDependencies\": {\n    \"@types/body-parser\": \"^1.19.0\",\n    \"@types/dotenv\": \"^8.2.0\",\n    \"@types/express\": \"^4.17.8\",\n    \"@types/mysql\": \"^2.15.16\"\n  }\n}\n"
  },
  {
    "path": "typescript-mysql-quickstart/source/config/config.ts",
    "content": "import dotenv from 'dotenv';\n\ndotenv.config();\n\nconst MYSQL_HOST = process.env.MYSQL_HOST || 'localhost';\nconst MYSQL_DATABASE = process.env.MYSQL_DATABASE || 'supercooldb';\nconst MYSQL_USER = process.env.MYSQL_HOST || 'superuser';\nconst MYSQL_PASS = process.env.MYSQL_HOST || 'roseville';\n\nconst MYSQL = {\n    host: MYSQL_HOST,\n    database: MYSQL_DATABASE,\n    user: MYSQL_USER,\n    pass: MYSQL_PASS\n};\n\nconst SERVER_HOSTNAME = process.env.SERVER_HOSTNAME || 'localhost';\nconst SERVER_PORT = process.env.SERVER_PORT || 1337;\n\nconst SERVER = {\n    hostname: SERVER_HOSTNAME,\n    port: SERVER_PORT\n};\n\nconst config = {\n    mysql: MYSQL,\n    server: SERVER\n};\n\nexport default config;\n"
  },
  {
    "path": "typescript-mysql-quickstart/source/config/logging.ts",
    "content": "const info = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.info(`[${getTimeStamp()}] [INFO] [${namespace}] ${message}`, object);\n    } else {\n        console.info(`[${getTimeStamp()}] [INFO] [${namespace}] ${message}`);\n    }\n};\n\nconst warn = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.warn(`[${getTimeStamp()}] [WARN] [${namespace}] ${message}`, object);\n    } else {\n        console.warn(`[${getTimeStamp()}] [WARN] [${namespace}] ${message}`);\n    }\n};\n\nconst error = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.error(`[${getTimeStamp()}] [ERROR] [${namespace}] ${message}`, object);\n    } else {\n        console.error(`[${getTimeStamp()}] [ERROR] [${namespace}] ${message}`);\n    }\n};\n\nconst debug = (namespace: string, message: string, object?: any) => {\n    if (object) {\n        console.debug(`[${getTimeStamp()}] [DEBUG] [${namespace}] ${message}`, object);\n    } else {\n        console.debug(`[${getTimeStamp()}] [DEBUG] [${namespace}] ${message}`);\n    }\n};\n\nconst getTimeStamp = (): string => {\n    return new Date().toISOString();\n};\n\nexport default {\n    info,\n    warn,\n    error,\n    debug\n};\n"
  },
  {
    "path": "typescript-mysql-quickstart/source/config/mysql.ts",
    "content": "import mysql from 'mysql';\nimport config from './config';\n\nconst params = {\n    user: config.mysql.user,\n    password: config.mysql.pass,\n    host: config.mysql.host,\n    database: config.mysql.database\n};\n\nconst Connect = async () =>\n    new Promise<mysql.Connection>((resolve, reject) => {\n        const connection = mysql.createConnection(params);\n\n        connection.connect((error) => {\n            if (error) {\n                reject(error);\n                return;\n            }\n\n            resolve(connection);\n        });\n    });\n\nconst Query = async (connection: mysql.Connection, query: string) =>\n    new Promise((resolve, reject) => {\n        connection.query(query, connection, (error, result) => {\n            if (error) {\n                reject(error);\n                return;\n            }\n\n            resolve(result);\n        });\n    });\n\nexport { Connect, Query };\n"
  },
  {
    "path": "typescript-mysql-quickstart/source/controllers/book.ts",
    "content": "import { NextFunction, Request, Response } from 'express';\nimport logging from '../config/logging';\nimport { Connect, Query } from '../config/mysql';\n\nconst NAMESPACE = 'Books';\n\nconst createBook = async (req: Request, res: Response, next: NextFunction) => {\n    logging.info(NAMESPACE, 'Inserting books');\n\n    let { author, title } = req.body;\n\n    let query = `INSERT INTO books (author, title) VALUES (\"${author}\", \"${title}\")`;\n\n    Connect()\n        .then((connection) => {\n            Query(connection, query)\n                .then((result) => {\n                    logging.info(NAMESPACE, 'Book created: ', result);\n\n                    return res.status(200).json({\n                        result\n                    });\n                })\n                .catch((error) => {\n                    logging.error(NAMESPACE, error.message, error);\n\n                    return res.status(200).json({\n                        message: error.message,\n                        error\n                    });\n                })\n                .finally(() => {\n                    logging.info(NAMESPACE, 'Closing connection.');\n                    connection.end();\n                });\n        })\n        .catch((error) => {\n            logging.error(NAMESPACE, error.message, error);\n\n            return res.status(200).json({\n                message: error.message,\n                error\n            });\n        });\n};\n\nconst getAllBooks = async (req: Request, res: Response, next: NextFunction) => {\n    logging.info(NAMESPACE, 'Getting all books.');\n\n    let query = 'SELECT * FROM books';\n\n    Connect()\n        .then((connection) => {\n            Query(connection, query)\n                .then((results) => {\n                    logging.info(NAMESPACE, 'Retrieved books: ', results);\n\n                    return res.status(200).json({\n                        results\n                    });\n                })\n                .catch((error) => {\n                    logging.error(NAMESPACE, error.message, error);\n\n                    return res.status(200).json({\n                        message: error.message,\n                        error\n                    });\n                })\n                .finally(() => {\n                    logging.info(NAMESPACE, 'Closing connection.');\n                    connection.end();\n                });\n        })\n        .catch((error) => {\n            logging.error(NAMESPACE, error.message, error);\n\n            return res.status(200).json({\n                message: error.message,\n                error\n            });\n        });\n};\n\nexport default { createBook, getAllBooks };\n"
  },
  {
    "path": "typescript-mysql-quickstart/source/interfaces/book.ts",
    "content": "export default interface IBook {\n    id: number;\n    author: string;\n    title: string;\n}\n"
  },
  {
    "path": "typescript-mysql-quickstart/source/routes/book.ts",
    "content": "import express from 'express';\nimport controller from '../controllers/book';\n\nconst router = express.Router();\n\nrouter.post('/create/book', controller.createBook);\nrouter.get('/get/books', controller.getAllBooks);\n\nexport = router;\n"
  },
  {
    "path": "typescript-mysql-quickstart/source/server.ts",
    "content": "import http from 'http';\nimport bodyParser from 'body-parser';\nimport express from 'express';\nimport logging from './config/logging';\nimport config from './config/config';\nimport bookRoutes from './routes/book';\n\nconst NAMESPACE = 'Server';\nconst router = express();\n\n/** Log the request */\nrouter.use((req, res, next) => {\n    /** Log the req */\n    logging.info(NAMESPACE, `METHOD: [${req.method}] - URL: [${req.url}] - IP: [${req.socket.remoteAddress}]`);\n\n    res.on('finish', () => {\n        /** Log the res */\n        logging.info(NAMESPACE, `METHOD: [${req.method}] - URL: [${req.url}] - STATUS: [${res.statusCode}] - IP: [${req.socket.remoteAddress}]`);\n    })\n    \n    next();\n});\n\n/** Parse the body of the request */\nrouter.use(bodyParser.urlencoded({ extended: true }));\nrouter.use(bodyParser.json());\n\n/** Rules of our API */\nrouter.use((req, res, next) => {\n    res.header('Access-Control-Allow-Origin', '*');\n    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');\n\n    if (req.method == 'OPTIONS') {\n        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');\n        return res.status(200).json({});\n    }\n\n    next();\n});\n\n/** Routes go here */\nrouter.use('/books', bookRoutes);\n\n/** Error handling */\nrouter.use((req, res, next) => {\n    const error = new Error('Not found');\n\n    res.status(404).json({\n        message: error.message\n    });\n});\n\nconst httpServer = http.createServer(router);\n\nhttpServer.listen(config.server.port, () => logging.info(NAMESPACE, `Server is running ${config.server.hostname}:${config.server.port}`));\n"
  },
  {
    "path": "typescript-mysql-quickstart/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    /* Visit https://aka.ms/tsconfig.json to read more about this file */\n\n    /* Basic Options */\n    // \"incremental\": true,                   /* Enable incremental compilation */\n    \"target\": \"es5\",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */\n    \"module\": \"commonjs\",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */\n    // \"lib\": [],                             /* Specify library files to be included in the compilation. */\n    // \"allowJs\": true,                       /* Allow javascript files to be compiled. */\n    // \"checkJs\": true,                       /* Report errors in .js files. */\n    // \"jsx\": \"preserve\",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */\n    // \"declaration\": true,                   /* Generates corresponding '.d.ts' file. */\n    // \"declarationMap\": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */\n    // \"sourceMap\": true,                     /* Generates corresponding '.map' file. */\n    // \"outFile\": \"./\",                       /* Concatenate and emit output to single file. */\n    \"outDir\": \"./build\",                        /* Redirect output structure to the directory. */\n    // \"rootDir\": \"./\",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */\n    // \"composite\": true,                     /* Enable project compilation */\n    // \"tsBuildInfoFile\": \"./\",               /* Specify file to store incremental compilation information */\n    // \"removeComments\": true,                /* Do not emit comments to output. */\n    // \"noEmit\": true,                        /* Do not emit outputs. */\n    // \"importHelpers\": true,                 /* Import emit helpers from 'tslib'. */\n    // \"downlevelIteration\": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */\n    // \"isolatedModules\": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */\n\n    /* Strict Type-Checking Options */\n    \"strict\": true,                           /* Enable all strict type-checking options. */\n    // \"noImplicitAny\": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */\n    // \"strictNullChecks\": true,              /* Enable strict null checks. */\n    // \"strictFunctionTypes\": true,           /* Enable strict checking of function types. */\n    // \"strictBindCallApply\": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */\n    // \"strictPropertyInitialization\": true,  /* Enable strict checking of property initialization in classes. */\n    // \"noImplicitThis\": true,                /* Raise error on 'this' expressions with an implied 'any' type. */\n    // \"alwaysStrict\": true,                  /* Parse in strict mode and emit \"use strict\" for each source file. */\n\n    /* Additional Checks */\n    // \"noUnusedLocals\": true,                /* Report errors on unused locals. */\n    // \"noUnusedParameters\": true,            /* Report errors on unused parameters. */\n    // \"noImplicitReturns\": true,             /* Report error when not all code paths in function return a value. */\n    // \"noFallthroughCasesInSwitch\": true,    /* Report errors for fallthrough cases in switch statement. */\n\n    /* Module Resolution Options */\n    // \"moduleResolution\": \"node\",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */\n    // \"baseUrl\": \"./\",                       /* Base directory to resolve non-absolute module names. */\n    // \"paths\": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */\n    // \"rootDirs\": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */\n    // \"typeRoots\": [],                       /* List of folders to include type definitions from. */\n    // \"types\": [],                           /* Type declaration files to be included in compilation. */\n    // \"allowSyntheticDefaultImports\": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */\n    \"esModuleInterop\": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */\n    // \"preserveSymlinks\": true,              /* Do not resolve the real path of symlinks. */\n    // \"allowUmdGlobalAccess\": true,          /* Allow accessing UMD globals from modules. */\n\n    /* Source Map Options */\n    // \"sourceRoot\": \"\",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */\n    // \"mapRoot\": \"\",                         /* Specify the location where debugger should locate map files instead of generated locations. */\n    // \"inlineSourceMap\": true,               /* Emit a single file with source maps instead of having a separate file. */\n    // \"inlineSources\": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */\n\n    /* Experimental Options */\n    // \"experimentalDecorators\": true,        /* Enables experimental support for ES7 decorators. */\n    // \"emitDecoratorMetadata\": true,         /* Enables experimental support for emitting type metadata for decorators. */\n\n    /* Advanced Options */\n    \"skipLibCheck\": true,                     /* Skip type checking of declaration files. */\n    \"forceConsistentCasingInFileNames\": true  /* Disallow inconsistently-cased references to the same file. */\n  }\n}\n"
  }
]