From cb93764c403198f9a6fd22ad5142051606bdce93 Mon Sep 17 00:00:00 2001 From: Carlos Guadir Date: Tue, 7 Sep 2021 22:43:58 -0500 Subject: [PATCH 1/8] Refactor --- .eslintrc | 60 +++-- .gitignore | 2 + package.json | 30 ++- src/__test__/client.test.ts | 270 ++++------------------- src/client/services/MutationsService.ts | 4 +- src/client/services/QueriesService.ts | 111 +--------- src/client/services/Service.ts | 6 +- src/client/services/index.ts | 2 +- src/scripts/postinstall.ts | 1 - src/scripts/sync.ts | 105 +++++---- src/tests/cli/env.test | 1 + src/tests/cli/introspection.spec.test.ts | 43 ++++ src/utils/ScalarsClient.mustache | 19 +- src/utils/ScalarsClientManager.mustache | 2 +- src/utils/Service.mustache | 2 +- src/utils/interfaces.ts | 1 - src/utils/introspect.ts | 104 +++------ src/utils/template.mustache | 2 +- tsconfig.json | 26 +-- 19 files changed, 245 insertions(+), 546 deletions(-) delete mode 100644 src/scripts/postinstall.ts create mode 100644 src/tests/cli/env.test create mode 100644 src/tests/cli/introspection.spec.test.ts diff --git a/.eslintrc b/.eslintrc index 7d30070..7693103 100644 --- a/.eslintrc +++ b/.eslintrc @@ -5,33 +5,63 @@ "plugin:@typescript-eslint/recommended" ], "parser": "@typescript-eslint/parser", - "plugins": ["@typescript-eslint"], + "plugins": [ + "@typescript-eslint", + "simple-import-sort" + ], "parserOptions": { - "project": "tsconfig.json" + "project": "./tsconfig.json" }, "root": true, + "ignorePatterns": [ "**/*.test.ts"], "rules": { + "simple-import-sort/imports": "error", + "simple-import-sort/exports": "error", + "object-curly-newline": ["error", { + "ImportDeclaration": { + "multiline": true + }, + "ExportDeclaration": { + "multiline": true, + "minProperties": 3 + } + }], + "no-useless-escape": "off", + "no-console": [ "error", { "allow": [ "error", "info" ] } ], + "no-tabs": "off", + "no-mixed-spaces-and-tabs": "error", + "semi": [ 2, "never" ], + "@typescript-eslint/no-unused-vars": [ "error", { "argsIgnorePattern": "^_" } ], "@typescript-eslint/restrict-plus-operands": "error", + "@typescript-eslint/ban-ts-ignore": "off", + "@typescript-eslint/ban-types": "off", "@typescript-eslint/no-inferrable-types": "off", - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/explicit-module-boundary-types": "off", - "@typescript-eslint/indent": ["error", 4, { - "FunctionDeclaration": {"parameters": "first"}, - "FunctionExpression": {"parameters": "first"} - }], - "@typescript-eslint/no-use-before-define": ["error", { + "@typescript-eslint/no-explicit-any": "warn", + "@typescript-eslint/indent": [ "error", 4, { + "FunctionDeclaration": { "parameters": "first" }, + "FunctionExpression": { "parameters": "first" } + } ], + "@typescript-eslint/type-annotation-spacing": "error", + "@typescript-eslint/no-use-before-define": [ "error", { "variables": true, "functions": true - }], - "no-case-declarations": "off", - "quotes": ["error", "single", { + } ], + "quotes": [ "error", "single", { "allowTemplateLiterals": true - }], - "semi": [ "error", "never" ], - "camelcase": "off", + } ], + "array-bracket-spacing": [ "error", "always" ], + "comma-spacing": [ "error", { "before": false, "after": true } ], "object-curly-spacing": [ "error", "always" ], + "space-unary-ops": [ + 2, { + "words": true, + "nonwords": true + } + ], "block-spacing": [ "error", "always" ], "space-in-parens": [ "error", "always" ], + "max-lines": [ "error", { "max": 500, "skipBlankLines": true, "skipComments": true } ], + "max-lines-per-function": [ "error", 70 ], "space-infix-ops": [ "error", { "int32Hint": true } ] } } diff --git a/.gitignore b/.gitignore index 2305373..86f1593 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ yarn.lock yarn-error.log package-lock.json +test-report.xml +tsconfig.tsbuildinfo node_modules dist .env.dev diff --git a/package.json b/package.json index 0533580..a7a824f 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,7 @@ { - "name": "@juaji/scalars-cli", - "version": "1.2.22", - "description": "Client for scalars APIs", - "author": "LuisDanilo ", + "name": "@scalars/cli", + "version": "1.2.23", + "description": "Client for scalars application", "license": "MIT", "main": "dist/index.js", "scripts": { @@ -10,7 +9,9 @@ "copy": "yarn run mkdir && cp src/utils/ScalarsClient.mustache dist/templates/ScalarsClient.mustache", "build": "rimraf dist && tsc && rollup -c && rimraf dist/dts && yarn run copy", "test": "yarn build && node dist/sync.js && jest --detectOpenHandles --forceExit --testTimeout=540000", - "jest": "jest --testTimeout=540000 --runInBand" + "jest": "jest --testTimeout=540000 --runInBand", + "prepublish": "yarn build", + "postinstall": "yarn build" }, "files": [ "dist" @@ -19,18 +20,25 @@ "keywords": [ "scalars", "sdk", - "scalars-cli", + "cli", + "graphql", + "serverless", + "baas", "madrov" ], "devDependencies": { "@rollup/plugin-typescript": "^8.2.1", "@types/inquirer": "^7.3.3", + "@types/inquirer-fuzzy-path": "^2.3.2", + "@scalars/cli": "file:./dist/dts", "@types/jest": "^26.0.24", "@types/mustache": "^4.1.1", "@types/rollup__plugin-virtual": "^2.0.1", "@typescript-eslint/eslint-plugin": "^4.28.1", "@typescript-eslint/parser": "^4.28.1", + "child-process": "^1.0.2", "eslint": "^7.29.0", + "eslint-plugin-simple-import-sort": "^7.0.0", "jest": "^27.0.6", "jest-sonar-reporter": "^2.0.0", "rimraf": "^3.0.2", @@ -38,12 +46,13 @@ "rollup-plugin-terser": "^7.0.2", "ts-jest": "^27.0.3", "tslib": "^2.3.0", - "typescript": "^4.3.4" + "typescript": "^4.3.4", + "yargs": "^17.0.1" }, "bin": { "scalars": "dist/sync.js" }, - "repository": "https://gitlab.com/LuisDanilo/scalars-cli", + "repository": "https://gitlab.com/scalars/cli", "dependencies": { "@apollo/client": "^3.3.21", "@graphql-codegen/cli": "^2.0.1", @@ -53,13 +62,12 @@ "@types/node-fetch": "^2.5.11", "dotenv": "^10.0.0", "graphql": "^15.5.1", + "graphql-tag": "^2.12.5", "inquirer": "^8.1.2", "inquirer-fuzzy-path": "^2.3.0", "mustache": "^4.2.0", "node-fetch": "^2.6.1", "react": "^17.0.2", - "tsc-prog": "^2.2.1", - "yargs": "^17.0.1", - "graphql-tag": "^2.12.5" + "tsc-prog": "^2.2.1" } } diff --git a/src/__test__/client.test.ts b/src/__test__/client.test.ts index c54512e..480259d 100644 --- a/src/__test__/client.test.ts +++ b/src/__test__/client.test.ts @@ -1,12 +1,13 @@ -import { IFaq, IProfile, IRegistration, ProfileSelect, ScalarsClient } from '../../dist/index' +// @ts-ignore +import { Profile, ProfileSelect, ScalarsClient, ScalarsClientConfig } from '../../dist/index' import { faqSeeds, registrationSeeds } from './client.seeds' -const client: ScalarsClient = new ScalarsClient() +const client: ScalarsClient = new ScalarsClient( { endpoint: '', authorization: ''} as ScalarsClientConfig ) const idRegex: RegExp = new RegExp( `[0-9a-fA-F]{16}` ) const dateRegex: RegExp = new RegExp( `[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T(2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]\\.[0-9]{3}Z` ) const emailRegex: RegExp = new RegExp( `[a-zA-Z]+@[a-zA-Z]+.+` ) -const { objectContaining, stringContaining, anything, stringMatching, arrayContaining } = expect +const { objectContaining, stringContaining, stringMatching, arrayContaining } = expect const { floor, random } = Math describe( `Registration`, () => { @@ -18,7 +19,7 @@ describe( `Registration`, () => { .registrations( { select: { id: true } } ) - .then( ( res: Array ) => { + .then( ( res: Array ) => { expect( res ).toEqual( arrayContaining( [objectContaining( { id: stringMatching( idRegex ), } )] ) ) @@ -36,7 +37,7 @@ describe( `Registration`, () => { select: { email: true, name: true, createdAt: true, updatedAt: true, linkedin: true }, where: { id: registrationId } } ) - .then( ( res: IRegistration ) => { + .then( ( res: any ) => { expect( res ).toEqual( objectContaining( { email: stringMatching( emailRegex ), name: stringContaining( '' ), @@ -61,7 +62,7 @@ describe( `Registration`, () => { linkedin: createRegistration.linkedin } } ) - .then( ( res: IRegistration ) => { + .then( ( res: any ) => { expect( res ).toEqual( objectContaining( { id: stringMatching( idRegex ) } ) ) @@ -78,7 +79,7 @@ describe( `Registration`, () => { where: { id: registrationId }, data: { email: updateRegistration.email, name: updateRegistration.name } } ) - .then( ( res: IRegistration ) => { + .then( ( res: any ) => { expect( res ).toEqual( objectContaining( { id: stringContaining( registrationId ), name: stringContaining( updateRegistration.name ), @@ -98,7 +99,7 @@ describe( `Registration`, () => { select: { id: true, name: true, email: true, createdAt: true, linkedin: true, updatedAt: true }, where: { id: registrationId } } ) - .then( ( res: IRegistration ) => { + .then( ( res: any ) => { expect( res ).toEqual( objectContaining( { id: stringContaining( registrationId ), name: stringContaining( updateRegistration.name ), @@ -123,7 +124,7 @@ describe( `Faq`, () => { .faqs( { select: { id: true } } ) - .then( ( res: Array ) => { + .then( ( res: Array ) => { expect( res ).toEqual( arrayContaining( [objectContaining( { id: stringMatching( idRegex ) } )] ) ) @@ -141,7 +142,7 @@ describe( `Faq`, () => { select: { answer: true, question: true, createdAt: true, updatedAt: true }, where: { id: faqId } } ) - .then( ( res: IFaq ) => { + .then( ( res: any ) => { expect( res ).toEqual( objectContaining( { answer: stringContaining( '' ), question: stringContaining( '' ), @@ -166,7 +167,7 @@ describe( `Faq`, () => { answer: createFaq.answer } } ) - .then ( ( res: IFaq ) => { + .then ( ( res: any ) => { expect( res ).toEqual( objectContaining( { id: stringMatching( idRegex ) } ) ) @@ -183,7 +184,7 @@ describe( `Faq`, () => { where: { id: faqId }, data: { question: updateFaq.question } } ) - .then( ( res: IFaq ) => { + .then( ( res: any ) => { expect( res ).toEqual( objectContaining( { id: stringContaining( faqId ), question: stringContaining( updateFaq.question ), @@ -202,7 +203,7 @@ describe( `Faq`, () => { select: { id: true, answer: true, question: true, createdAt: true, updatedAt: true }, where: { id: faqId } } ) - .then( ( res: IFaq ) => { + .then( ( res: any ) => { expect( res ).toEqual( objectContaining( { id: stringContaining( faqId ), question: stringContaining( updateFaq.question ), @@ -217,67 +218,8 @@ describe( `Faq`, () => { } ) } ) -describe( `Answers`, () => { - test( `Should read answer`, ( done ) => { - done() - } ) - test( `Should create answer`, ( done ) => { - done() - } ) - test( `Should update answer`, ( done ) => { - done() - } ) - test( `Should delete answer`, ( done ) => { - done() - } ) -} ) - -describe( `Skill`, () => { - test( `Should read skill`, ( done )=>{ - done() - } ) - test( `Should create skill`, ( done ) => { - done() - } ) - test( `Should update skill`, ( done ) => { - done() - } ) - test( `Should delete skill`, ( done ) => { - done() - } ) -} ) - -describe( `Interest`, () => { - test( `Should read interest`, ( done ) => { - done() - } ) - test( `Should create interest`, ( done ) => { - done() - } ) - test( `Should update interest`, ( done ) => { - done() - } ) - test( `Should delete interest`, ( done ) => { - done() - } ) -} ) - describe( `Profile`, () => { test( `Should read profile`, ( done ) => { - // 1st - // client - // .doQuery( - // `query profile($where: ProfileWhereUniqueInput!) { profile(where: $where) { id } }`, - // { where: { email: 'luis@madrov.com' } } - // ) - // .then( ( res: Record<'profile', any> ) => { - // console.log( res.profile ) - // } ) - // .catch( ( err: unknown ) => { - // console.log( err ) - // } ) - // .finally( done ) - // 2nd const profileSelect: ProfileSelect = { id: true, email: true, description: true, phone: true, sentConnections: { @@ -335,185 +277,57 @@ describe( `Profile`, () => { select: profileSelect, where: { user: { username: '+573145463091' } } } ) - .then ( ( res: Array ) => { + .then ( ( res: Array ) => { console.log( res ) done() - // expect( res ).toEqual( expect.objectContaining( { - // id: expect.stringMatching( idRegex ), - // email: expect.stringContaining( `andres` ), - // description: expect.stringContaining( `Desarrollador Backend` ), - // phone: null, - // sentConnections: expect.arrayContaining( [expect.objectContaining( { - // id: expect.stringMatching( idRegex ), - // createdAt: expect.stringMatching( dateRegex ), - // updatedAt: expect.stringMatching( dateRegex ), - // status: expect.anything(), - // sender: expect.objectContaining( { - // id: expect.stringMatching( idRegex ), - // email: expect.stringMatching( emailRegex ), - // user: expect.objectContaining( { - // name: expect.anything(), - // id: expect.stringMatching( idRegex ), - // createdAt: expect.stringMatching( dateRegex ), - // } ) - // } ), - // receiver: expect.objectContaining( { - // id: expect.stringMatching( idRegex ), - // email: expect.stringMatching( emailRegex ), - // user: expect.objectContaining( { - // name: expect.anything(), - // id: expect.stringMatching( idRegex ), - // createdAt: expect.stringMatching( dateRegex ) - // } ) - // } ) - // } )] ), - // founder_projects: expect.arrayContaining( [expect.objectContaining( { - // name: expect.anything(), - // founders: expect.arrayContaining( [expect.objectContaining( { - // email: expect.stringMatching( emailRegex ) - // } )] ), - // requests: expect.arrayContaining( [expect.objectContaining( { - // id: expect.stringMatching( idRegex ), - // status: expect.anything(), - // createdAt: expect.stringMatching( dateRegex ), - // invitee: expect.objectContaining( { - // email: expect.stringMatching( emailRegex ) - // } ), - // inviter: expect.objectContaining( { - // email: expect.stringMatching( emailRegex ) - // } ), - // project: expect.objectContaining( { - // name: expect.anything() - // } ) - // } )] ) - // } )] ), - // // receivedConnection: expect.arrayContaining( [expect.objectContaining( { - // // id: expect.stringMatching( idRegex ), - // // createdAt: expect.stringMatching( dateRegex ), - // // updatedAt: expect.stringMatching( dateRegex ), - // // status: expect.anything(), - // // sender: expect.objectContaining( { - // // id: expect.stringMatching( idRegex ), - // // email: expect.stringMatching( emailRegex ), - // // user: expect.objectContaining( { - // // name: expect.anything(), - // // id: expect.stringMatching( idRegex ), - // // createdAt: expect.stringMatching( dateRegex ), - // // } ) - // // } ), - // // receiver: expect.objectContaining( { - // // id: expect.stringMatching( idRegex ), - // // email: expect.stringMatching( emailRegex ), - // // user: expect.objectContaining( { - // // name: expect.anything(), - // // id: expect.stringMatching( idRegex ), - // // createdAt: expect.stringMatching( dateRegex ) - // // } ) - // // } ) - // // } )] ) - // } ) ) } ) .catch( ( err: unknown ) => { console.log( err ) } ) } ) - test( `Should create profile`, ( done ) => { - done() - } ) - test( `Should update profile`, ( done ) => { - done() - } ) - test( `Should delete profile`, ( done ) => { - done() - } ) + test.todo( `Should create profile`) + test.todo( `Should update profile`) + test.todo( `Should delete profile`) } ) describe( `Chat`, () => { - test( `Should read chat`, ( done ) => { - done() - } ) - test( `Should create chat`, ( done ) => { - done() - } ) - test( `Should update chat`, ( done ) => { - done() - } ) - test( `Should delete chat`, ( done ) => { - done() - } ) + test.todo( `Should read chat`) + test.todo( `Should create chat`) + test.todo( `Should update chat`) + test.todo( `Should delete chat`) } ) describe( `Message`, () => { - test( `Should read message`, ( done ) => { - done() - } ) - test( `Should create message`, ( done ) => { - done() - } ) - test( `Should update message`, ( done ) => { - done() - } ) - test( `Should delete message`, ( done ) => { - done() - } ) + test.todo( `Should read message`) + test.todo( `Should create message`) + test.todo( `Should update message`) + test.todo( `Should delete message`) } ) describe( `Connection`, () => { - test( `Should read connection`, ( done ) => { - done() - } ) - test( `Should create connection`, ( done ) => { - done() - } ) - test( `Should update connection`, ( done ) => { - done() - } ) - test( `Should delete connection`, ( done ) => { - done() - } ) + test.todo( `Should read connection`) + test.todo( `Should create connection`) + test.todo( `Should update connection`) + test.todo( `Should delete connection`) } ) describe( `Project`, () => { - test( `Should read project`, ( done ) => { - done() - } ) - test( `Should create project`, ( done ) => { - done() - } ) - test( `Should update project`, ( done ) => { - done() - } ) - test( `Should delete project`, ( done ) => { - done() - } ) + test.todo( `Should read project`) + test.todo( `Should create project`) + test.todo( `Should update project`) + test.todo( `Should delete project`) } ) describe( `Request`, () => { - test( `Should read request`, ( done ) => { - done() - } ) - test( `Should create request`, ( done ) => { - done() - } ) - test( `Should update request`, ( done ) => { - done() - } ) - test( `Should delete request`, ( done ) => { - done() - } ) + test.todo( `Should read request`) + test.todo( `Should create request`) + test.todo( `Should update request`) + test.todo( `Should delete request`) } ) describe( `Comment`, () => { - test( `Should read comment`, ( done ) => { - done() - } ) - test( `Should create comment`, ( done ) => { - done() - } ) - test( `Should update comment`, ( done ) => { - done() - } ) - test( `Should delete comment`, ( done ) => { - done() - } ) + test.todo( `Should read comment` ) + test.todo( `Should create comment`) + test.todo( `Should update comment`) + test.todo( `Should delete comment`) } ) diff --git a/src/client/services/MutationsService.ts b/src/client/services/MutationsService.ts index b60a2cb..b0d8797 100644 --- a/src/client/services/MutationsService.ts +++ b/src/client/services/MutationsService.ts @@ -1,5 +1,3 @@ import { Service } from './Service' -export class MutationsService extends Service { - -} +export class MutationsService extends Service {} diff --git a/src/client/services/QueriesService.ts b/src/client/services/QueriesService.ts index e5f64d9..74cefe3 100644 --- a/src/client/services/QueriesService.ts +++ b/src/client/services/QueriesService.ts @@ -1,110 +1,3 @@ -class Service { -} +class Service { } -export class QueriesService extends Service { - // getAnswer ( where: Record, ) { - // console.log( 'ho' ) - // } - // getAnswers () { - // } - // getAppclient () { - // } - // getAppclients () { - // } - // getAssetsconfig () { - // } - // getAssetsconfigs () { - // } - // getAuthcodegrant () { - // } - // getAuthcodegrants () { - // } - // getAuthrole () { - // } - // getAuthroles () { - // } - // getAuthsession () { - // } - // getAuthsessions () { - // } - // getAuthuser () { - // } - // getAuthusers () { - // } - // getChat () { - // } - // getChats () { - // } - // getComment () { - // } - // getComments () { - // } - // getConnection () { - // } - // getConnections () { - // } - // getCountry () { - // } - // getCountries () { - // } - // getDatapermission () { - // } - // getDatapermissions () { - // } - // getDocumentfile () { - // } - // getDocumentfiles () { - // } - // getFaq () { - // } - // getFaqs () { - // } - // getImagefile () { - // } - // getImagefiles () { - // } - // getInterest () { - // } - // getInterests () { - // } - // getMessage () { - // } - // getMessages () { - // } - // getMimetype () { - // } - // getMimetypes () { - // } - // getProfile () { - // } - // getProfiles () { - // } - // getProject () { - // } - // getProjects () { - // } - // getRegistration () { - // } - // getRegistrations () { - // } - // getRequest () { - // } - // getRequests () { - // } - // getSkill () { - // } - // getSkills () { - // } - // getSoundfile () { - // } - // getSoundfiles () { - // } - // getTrigger () { - // } - // getTriggers () { - // } - // getVideofile () { - // } - // getVideofiles () { - // } -} +export class QueriesService extends Service {} diff --git a/src/client/services/Service.ts b/src/client/services/Service.ts index 5016a87..a2cd213 100644 --- a/src/client/services/Service.ts +++ b/src/client/services/Service.ts @@ -1,5 +1 @@ -export abstract class Service { - // protected async doQuery ( query: string, variables: V ): Promise { - // - // } -} +export abstract class Service { } diff --git a/src/client/services/index.ts b/src/client/services/index.ts index d39d996..d49a2ef 100644 --- a/src/client/services/index.ts +++ b/src/client/services/index.ts @@ -1,2 +1,2 @@ -export * from './QueriesService' export * from './MutationsService' +export * from './QueriesService' diff --git a/src/scripts/postinstall.ts b/src/scripts/postinstall.ts deleted file mode 100644 index 9ddc1c2..0000000 --- a/src/scripts/postinstall.ts +++ /dev/null @@ -1 +0,0 @@ -console.log( 'Maldita sea' ) diff --git a/src/scripts/sync.ts b/src/scripts/sync.ts index 28e72e0..2c466ee 100644 --- a/src/scripts/sync.ts +++ b/src/scripts/sync.ts @@ -1,28 +1,36 @@ -import { introspect } from '../utils/introspect' import { config } from 'dotenv' -import { join, resolve } from 'path' -import yargs from 'yargs' import inquirer from 'inquirer' -import * as fuzzyPath from 'inquirer-fuzzy-path' -// Inquirer setup +import fuzzyPath from 'inquirer-fuzzy-path' +import { join } from 'path' +import yargs from 'yargs' + +import { introspect } from '../utils/introspect' inquirer.registerPrompt( 'path', fuzzyPath ) +const succesMessage: string = ` +Introspection success ! + Enjoy your experience using Scalars + Happy codding!! +== Madrov team️ == +` + /** * Function that starts introspection * @param endpoint Endpoint to introspect - * @param clientId Client id to authorize introspection * @param clientPath Path where ScalarsClient.ts will be generated * @param soft Make soft introspection */ -const sync = ( endpoint: string, clientId: string, clientPath: string, soft: boolean ) => { +const sync = ( endpoint: string, clientPath: string, soft: boolean ) => { introspect( { endpoint, - clientId, clientPath, soft } ).then( () => { - // console.clear() - console.info( `Introspection success!\n\tEnjoy your experience using Scalars\n\tHappy codding!!\n== Madrov team️ ==` ) + console.info( succesMessage ) + process.exit( 0 ) + } ).catch( error => { + console.info( error ) + process.exit( - 1 ) } ) } @@ -31,57 +39,39 @@ const sync = ( endpoint: string, clientId: string, clientPath: string, soft: boo * @param interactive Flag to enable command line menu * @param endpoint Endpoint recovered from command line option "-e or --endpoint". * @param authorization Authorization recovered from command line option "-a or --authorization". + * @param env * @param prod Flag to use .env.prod file as introspection values, otherwise .env.dev is taken by default. + * @param soft */ -const loadEnvsAndIntrospect = ( interactive: boolean, endpoint: string | null, authorization: string | null, prod: boolean, soft: boolean ) => { - // endpoint final a usar +const loadEnvsAndIntrospect = ( + interactive: boolean, + endpoint: string | null, + authorization: string | null, + env: string | null, + prod: boolean, + soft: boolean +) => { let currentEndpoint: string | null = endpoint - // authorization final a usar, un string "client_id xxxxxx" oo un string jwt - let currentAuthorization: string | null = authorization - // Para cuando el menu esta habilitado, ruta por defecto en donde se exporta ScalarsClient.ts let clientPath: string = __dirname - // Bandera para errores varios - const { error, parsed } = config( { path: join( process.cwd(), `${prod ? '.env.prod' : '.env.dev'}` ) } ) - if ( !error && parsed ) { - // Environment variables loaded successfully - currentEndpoint = ( endpoint || parsed.SCALARS_ENDPOINT ) as string - currentAuthorization = ( authorization || parsed.SCALARS_CLIENT_ID ) as string + if ( env ) { + const { error, parsed } = config( { path: join( process.cwd(), `${env ? env : '.env'}` ) } ) + if ( ! error && parsed ) { + currentEndpoint = parsed.SCALARS_ENDPOINT as string + } } else { - console.info( `DOTENV ERROR: Couldn't load ${join( process.cwd(), `${prod ? '.env.prod' : '.env.dev'}` )}` ) - return + currentEndpoint = ( endpoint || process.env.SCALARS_ENDPOINT ) as string } - if ( !interactive ) { - // Have to make auto introspection - if ( currentEndpoint && currentAuthorization ) { - // endpoint and auth already configured, supplied through command line options - console.info( `Introspection with endpoint ${currentEndpoint}` ) - console.info( `Using client id ${currentAuthorization}` ) - sync( currentEndpoint as string, currentAuthorization as string, __dirname, soft ) - } else { - console.info( 'DOTENV ERROR: Environment variables loaded, but SCALARS_ENDPOINT or SCALARS_CLIENT_ID were not found' ) - return - } + if ( ! interactive && currentEndpoint ) { + console.info( `Start introspection ${currentEndpoint}` ) + sync( currentEndpoint as string, __dirname, soft ) } else { - // Have to make assisted introspection (with command line menu) inquirer.prompt( [ - { - type: 'confirm', - name: 'defaultEnvs', - message: `\tENDPOINT=${currentEndpoint}\n\tAUTHORIZATION=${currentAuthorization}\n♦♣♥♠ Are these your cards? (loaded from ${prod ? '.env.prod' : '.env.dev'})`, - }, { type: 'input', name: 'newEndpoint', message: `What's your scalars endpoint`, default: currentEndpoint, - when: ( answers ) => !answers.defaultEnvs - }, - { - type: 'input', - name: 'newClientId', - message: `What's your scalars client id`, - default: currentAuthorization, - when: ( answers ) => !answers.defaultEnvs + when: ( answers ) => ! answers.defaultEnvs }, { type: 'path', @@ -99,11 +89,10 @@ const loadEnvsAndIntrospect = ( interactive: boolean, endpoint: string | null, a } ] ).then( answers => { clientPath = answers.clientPath - if ( !answers.defaultEnvs && answers.newEndpoint && answers.newClientId ) { + if ( ! answers.defaultEnvs && answers.newEndpoint && answers.newClientId ) { currentEndpoint = answers.newEndpoint as string - currentAuthorization = answers.newClientId as string } - sync( currentEndpoint as string, currentAuthorization as string, clientPath, soft ) + sync( currentEndpoint as string, clientPath, soft ) } ) } @@ -112,12 +101,13 @@ const loadEnvsAndIntrospect = ( interactive: boolean, endpoint: string | null, a yargs( process.argv.slice( 2 ) ) .usage( `Usage: $0 ` ) .command( 'sync', 'Synchronize your client', ( { argv } ) => { - const prod: boolean = !!argv.p - const interactive: boolean = !!argv.i + const prod: boolean = !! argv.p + const interactive: boolean = !! argv.i const endpoint: string | null = ( argv.e as string ) || null const authorization: string | null = ( argv.a as string ) || null - const soft: boolean = !!argv.s - loadEnvsAndIntrospect( interactive, endpoint, authorization, prod, soft ) + const soft: boolean = !! argv.s + const env: string | null = argv.env as string || null + loadEnvsAndIntrospect( interactive, endpoint, authorization, env, prod, soft ) } ) .demand( 1, 'You must provide a valid scalars command' ) .help( 'h' ) @@ -131,6 +121,11 @@ yargs( process.argv.slice( 2 ) ) .option( 'e', { type: 'string', description: 'Make introspection with provided endpoint' } ) .alias( 'e', 'endpoint' ) .nargs( 'e', 1 ) + + .option( 'env', { type: 'string', description: 'Load enviroment file' } ) + .alias( 'env', 'enviroment' ) + .nargs( 'env', 1 ) + .option( 'a', { type: 'string', description: 'Make introspection with provided auth token' } ) .alias( 'a', 'authorization' ) .nargs( 'a', 1 ) diff --git a/src/tests/cli/env.test b/src/tests/cli/env.test new file mode 100644 index 0000000..b26bb8b --- /dev/null +++ b/src/tests/cli/env.test @@ -0,0 +1 @@ +SCALARS_ENDPOINT=https://devapp.kaury.co/app \ No newline at end of file diff --git a/src/tests/cli/introspection.spec.test.ts b/src/tests/cli/introspection.spec.test.ts new file mode 100644 index 0000000..b1ac424 --- /dev/null +++ b/src/tests/cli/introspection.spec.test.ts @@ -0,0 +1,43 @@ +import { exec } from 'child_process' + +describe( 'Suite cli introspection', () => { + it( 'should introspect with env in runtime', async ( ) => { + const status = await new Promise( ( resolve => { + const sync = exec( `SCALARS_ENDPOINT=https://devapp.kaury.co/app yarn ts-node dist/sync.js sync` ) + sync.on('exit', ( existCode: number ) => { + if ( existCode !== 0 ) { + resolve( false ) + return + } + resolve( true ) + } ) + } ) ) + expect( status ).toBeTruthy() + } ) + it( 'should introspect with env file path', async ( ) => { + const status = await new Promise( ( resolve => { + const sync = exec( `yarn ts-node dist/sync.js sync --env src/tests/cli/env.test` ) + sync.on('exit', ( existCode: number ) => { + if ( existCode !== 0 ) { + resolve( false ) + return + } + resolve( true ) + } ) + } ) ) + expect( status ).toBeTruthy() + } ) + it( 'should introspect with args command', async () => { + const status = await new Promise( ( resolve => { + const sync = exec( `yarn ts-node dist/sync.js sync --endpoint https://devapp.kaury.co/app` ) + sync.on('exit', ( existCode: number ) => { + if ( existCode !== 0 ) { + resolve( false ) + return + } + resolve( true ) + } ) + } ) ) + expect( status ).toBeTruthy() + } ) +} ) \ No newline at end of file diff --git a/src/utils/ScalarsClient.mustache b/src/utils/ScalarsClient.mustache index 8c6628c..e23f819 100644 --- a/src/utils/ScalarsClient.mustache +++ b/src/utils/ScalarsClient.mustache @@ -3,21 +3,6 @@ import { ApolloClient, ApolloLink, FetchPolicy, NormalizedCacheObject, InMemoryC import { setContext } from '@apollo/client/link/context' import { gql } from 'graphql-tag' import fetch from 'node-fetch' -import { config } from 'dotenv' -import { join } from 'path' - -let currentEndpoint: string = 'wololo'; -const prod: boolean = process.env.NODE_ENV === 'production'; -const { error, parsed } = config( { path: join( process.cwd(), `${prod ? '.env.prod' : '.env.dev'}` ) } ); - -if ( !error && parsed && parsed.SCALARS_ENDPOINT ) { - // Environment variables loaded successfully - currentEndpoint = parsed.SCALARS_ENDPOINT as string; -} else { - console.info( `ScalarsClientError: Couldn't load endpoint` ); -} - -// Service interface ApolloOptions { fetchPolicy?: FetchPolicy @@ -48,7 +33,7 @@ export class Service { constructor ( config: ScalarsClientConfig ) { this.scalarsApiClientManager = new ScalarsClientManager( - `${currentEndpoint}/api/v1`, + config.endpoint, config.authorization ) } @@ -206,7 +191,7 @@ export class MutationsService extends Service { // ScalarsClientManager -export type TokenFunction = ()=> string +export type TokenFunction = ()=> string | string export type FetchFunction = ( uri: string, options: any )=> Promise type ApolloClients = { diff --git a/src/utils/ScalarsClientManager.mustache b/src/utils/ScalarsClientManager.mustache index a29fabd..7d86534 100644 --- a/src/utils/ScalarsClientManager.mustache +++ b/src/utils/ScalarsClientManager.mustache @@ -2,7 +2,7 @@ import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, NormalizedCacheObjec import { setContext } from '@apollo/client/link/context'; import { ClientType } from './Service'; -export type TokenFunction = ()=> string +export type TokenFunction = ()=> string | string export type FetchFunction = ( uri: string, options: any )=> Promise type ApolloClients = { diff --git a/src/utils/Service.mustache b/src/utils/Service.mustache index 3baa568..128de47 100644 --- a/src/utils/Service.mustache +++ b/src/utils/Service.mustache @@ -32,7 +32,7 @@ export class Service { constructor ( config: ScalarsClientConfig ) { this.scalarsApiClientManager = new ScalarsClientManager( - `${process.env.SCALARS_ENDPOINT}/api/v1`, + config.endpoint, config.authorization ) } diff --git a/src/utils/interfaces.ts b/src/utils/interfaces.ts index 4330c22..8774c4a 100644 --- a/src/utils/interfaces.ts +++ b/src/utils/interfaces.ts @@ -1,6 +1,5 @@ export interface ScalarsClientConfig { endpoint: string - clientId: string, clientPath: string soft: boolean } diff --git a/src/utils/introspect.ts b/src/utils/introspect.ts index 22ed9b7..a15217c 100644 --- a/src/utils/introspect.ts +++ b/src/utils/introspect.ts @@ -1,10 +1,11 @@ import { generate } from '@graphql-codegen/cli' -import { join, resolve } from 'path' -import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs' +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs' import { render } from 'mustache' -import { ScalarsClientConfig } from './interfaces' +import { join, resolve } from 'path' import tsc, { TsConfigCompilerOptions } from 'tsc-prog' +import { ScalarsClientConfig } from './interfaces' + const selectTypes: Array> = [] const returnTypes: Array> = [] @@ -26,7 +27,7 @@ const generateTypedSchema = async ( scalarsEndpoint: string ): Promise = generates: { [join( __dirname, 'newTypes.ts' )]: { schema: scalarsEndpoint.endsWith( '/' ) ? `${scalarsEndpoint}api/v1` : `${scalarsEndpoint}/api/v1`, - plugins: ['typescript', 'typescript-operations'], + plugins: [ 'typescript', 'typescript-operations' ], } } }, false ) @@ -39,51 +40,10 @@ const generateTypedSchema = async ( scalarsEndpoint: string ): Promise = * fields that can be queried/are attached to each one. * @param config Client configuration (endpoint and client id) */ +// eslint-disable-next-line max-lines-per-function const updateScalarsClient = async ( operations: Record, config: ScalarsClientConfig ): Promise => { const outputPath = config.clientPath - !existsSync( outputPath ) && !!mkdirSync( outputPath, { recursive: true } ) - // const canPerformSoftIntrospection: boolean = config.soft - // && existsSync( resolve( outputPath, 'index.ts' ) ) - // if ( !canPerformSoftIntrospection ) { - // // ------------------------------------------------------------------------- - // // const scalarsClientManagerTemplate: string = readFileSync( - // // join( __dirname, 'templates', 'ScalarsClientManager.mustache' ) - // // ).toString() - // // writeFileSync( - // // resolve( outputPath, 'ScalarsClientManager.ts' ), - // // render( scalarsClientManagerTemplate, {} ) - // // ) - // // ------------------------------------------------------------------------- - // const scalarsClientTemplate: string = readFileSync( - // join( __dirname, 'templates', 'ScalarsClient.mustache' ) - // ).toString() - // writeFileSync( - // resolve( outputPath, 'index.ts' ), - // render( scalarsClientTemplate, {} ) - // ) - // // ------------------------------------------------------------------------- - // // const serviceTemplate: string = readFileSync( - // // join( __dirname, 'templates', 'Service.mustache' ) - // // ).toString() - // // writeFileSync( - // // resolve( outputPath, 'Service.ts' ), - // // render( serviceTemplate, {} ) - // // ) - // // ------------------------------------------------------------------------- - // // writeFileSync( - // // resolve( outputPath, 'index.ts' ), - // // `export * from './Service';\nexport * from './ScalarsClientManager';\nexport * from './ScalarsClient';\nexport * from './DefaultServices'; - // // ` - // // ) - // // ------------------------------------------------------------------------- - // // writeFileSync( - // // resolve( __dirname, 'index.ts' ), - // // `export * from './generated'` - // // ) - // } else { - // console.log( `Doing soft introspection!` ) - // } - // ------------------------------------------------------------------------- + ! existsSync( outputPath ) && !! mkdirSync( outputPath, { recursive: true } ) const schemaTypes = await generateTypedSchema( config.endpoint ) const defaultServicesTemplate: string = readFileSync( join( __dirname, 'templates', 'ScalarsClient.mustache' ) @@ -98,12 +58,10 @@ const updateScalarsClient = async ( operations: Record, config: Sca config } ) ) - // ------------------------------------------------------------------------- - // ------------------------------------------------------------------------- if ( outputPath === __dirname ) { try { - compile( [resolve( __dirname, 'index.ts' )], { + compile( [ resolve( __dirname, 'index.ts' ) ], { declaration: true, emitDeclarationOnly: false, target: 'es2019', @@ -116,8 +74,8 @@ const updateScalarsClient = async ( operations: Record, config: Sca outDir: __dirname, } ) } - catch ( e ) { - console.log( e ) + catch ( error ) { + console.info( error ) } } } @@ -150,7 +108,7 @@ const getFieldType = ( fieldType: Record ): Record => * This function builds types for operations responses * @param entity Entity to which the related queries or mutations responses will be build */ -const generateOperationsResponseTypes = ( entity: Record ): Record => { +const generateOperationsResponseTypes = ( entity: Record ): Record => { const selectType: Record = { name: `${entity.name}Select`, fields: entity.fields.map( ( field: Record ) => { @@ -160,7 +118,7 @@ const generateOperationsResponseTypes = ( entity: Record ): Record< } } ) } - if ( !selectTypes.some( select => select.name === selectType.name ) ) + if ( ! selectTypes.some( select => select.name === selectType.name ) ) selectTypes.push( selectType ) return selectType } @@ -201,7 +159,7 @@ const getOperationReturnType = ( type: Record, required: boolean = */ const getOperationArgType = ( arg: Record, required: boolean = false ): Record => { const { type: { kind, name, ofType } } = arg - let result: Record = {} + let result: Record = {} if ( /NON_NULL/gm.test( kind ) ) { result = getOperationArgType( { name: arg.name, type: ofType }, true ) } @@ -250,7 +208,7 @@ const getMutations = ( entity: Record, mutations: Array ) => { if ( getEntityFromOperation( mutation.type ) === entity.name ) { const operationReturn: Record = getOperationReturnType( mutation.type ) - if ( !returnTypes.some( ret => ret.type === operationReturn.type ) ) + if ( ! returnTypes.some( ret => ret.type === operationReturn.type ) ) returnTypes.push( operationReturn ) entityMutations.push( { operation: mutation.name, @@ -259,11 +217,11 @@ const getMutations = ( entity: Record, mutations: Array ) => getOperationArgType( arg ) ) - .sort( ( a: Record, b: Record ) => { - if ( a.requiredType && !b.requiredType ) { - return -1 + .sort( ( a: Record, b: Record ) => { + if ( a.requiredType && ! b.requiredType ) { + return - 1 } - if ( b.requiredType && !a.requiredType ) { + if ( b.requiredType && ! a.requiredType ) { return 1 } return 0 @@ -284,11 +242,11 @@ const getMutations = ( entity: Record, mutations: Array, queries: Array> ): Array> => { const entityQueries: Array> = [] - const select: Record = generateOperationsResponseTypes( entity ) + const select: Record = generateOperationsResponseTypes( entity ) queries.forEach( ( query: Record ) => { if ( getEntityFromOperation( query.type ) === entity.name ) { const operationReturn: Record = getOperationReturnType( query.type ) - if ( !returnTypes.some( ret => ret.type === operationReturn.type ) ) + if ( ! returnTypes.some( ret => ret.type === operationReturn.type ) ) returnTypes.push( operationReturn ) entityQueries.push( { operation: query.name, @@ -297,11 +255,11 @@ const getQueries = ( entity: Record, queries: Array ) => getOperationArgType( arg ) ) - .sort( ( a: Record, b: Record ) => { - if ( a.requiredType && !b.requiredType ) { - return -1 + .sort( ( a: Record, b: Record ) => { + if ( a.requiredType && ! b.requiredType ) { + return - 1 } - if ( b.requiredType && !a.requiredType ) { + if ( b.requiredType && ! a.requiredType ) { return 1 } return 0 @@ -327,18 +285,18 @@ const getServicesByOperations = ( objects: Array> ): Record< const queryObject: Record | undefined = objects .filter( ( object: Record ) => /^Query$/gm.test( object.name ) && - !/^.+Connection$/gm.test( object.name ) + ! /^.+Connection$/gm.test( object.name ) ).shift() const mutationObject: Record | undefined = objects .filter( ( object: Record ) => /^Mutation$/gm.test( object.name ) && - !/^.+Connection$/gm.test( object.name ) + ! /^.+Connection$/gm.test( object.name ) ).shift() const entitiesObjects: Array> = objects .filter( ( object: Record ) => - !/^Mutation$/gm.test( object.name ) && - !/^Query$/gm.test( object.name ) && - !/^.+Connection$/gm.test( object.name ) + ! /^Mutation$/gm.test( object.name ) && + ! /^Query$/gm.test( object.name ) && + ! /^.+Connection$/gm.test( object.name ) ) entitiesObjects.forEach( ( entity: Record ) => { operations.queries.push( ...getQueries( entity, queryObject?.fields ) ) @@ -357,7 +315,7 @@ const getIntrospectionFilteredByObjects = async ( scalarsEndpoint: string ): Pro generates: { 'introspection.json': { schema: scalarsEndpoint.endsWith( '/' ) ? `${scalarsEndpoint}api/v1` : `${scalarsEndpoint}/api/v1`, - plugins: ['introspection'], + plugins: [ 'introspection' ], config: { minify: false, descriptions: true, @@ -368,7 +326,7 @@ const getIntrospectionFilteredByObjects = async ( scalarsEndpoint: string ): Pro }, false ) const { '__schema': { types } }: Record = JSON.parse( content ) return types - .filter( ( type: any ) => /^OBJECT$/gm.test( type.kind ) && !/^__.+/gm.test( type.name ) ) + .filter( ( type: any ) => /^OBJECT$/gm.test( type.kind ) && ! /^__.+/gm.test( type.name ) ) } /** diff --git a/src/utils/template.mustache b/src/utils/template.mustache index f613940..5b1a4b6 100644 --- a/src/utils/template.mustache +++ b/src/utils/template.mustache @@ -5,7 +5,7 @@ import fetch from 'node-fetch'; import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, NormalizedCacheObject, FetchPolicy, gql } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; -type TokenFunction = ()=> string +type TokenFunction = ()=> string | string export interface ScalarsClientConfig { endpoint: string, diff --git a/tsconfig.json b/tsconfig.json index 3375185..6e44423 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,28 +14,6 @@ "rootDir": "src", }, "include": ["./src/**/*.ts"], - "exclude": [".dist/**/*.ts", "./src/__test__/**/*"] -// "exclude": [".dist/**/*.ts"] + "exclude": [ ".dist/**/*.ts" ] } -//{ -// "compilerOptions": { -// "allowJs": false, -// "allowSyntheticDefaultImports": true, -// "declaration": true, -// "declarationDir": "prebuild/types", -// "esModuleInterop": true, -// "outDir": "prebuild", -// "lib": ["es6", "dom", "es2016", "es2017"], -// "module": "CommonJS", -// "moduleResolution": "Node", -// "noEmit": false, -// "resolveJsonModule": true, -// "rootDir": "src", -// "sourceMap": false, -// "strict": true, -// "target": "ES5", -// "types": ["node"], -// }, -// "include": ["src/**/*"], -// "exclude": ["**/node_modules", "**/build", "**/dist", "**/*.md", "**/rollup.config.js"] -//} + From d16952c50a703f7af291fd9840909812edde694f Mon Sep 17 00:00:00 2001 From: Carlos Guadir Date: Tue, 7 Sep 2021 23:42:12 -0500 Subject: [PATCH 2/8] To delete --- package.json | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index a7a824f..c14e9e4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@scalars/cli", - "version": "1.2.23", + "version": "1.2.237", "description": "Client for scalars application", "license": "MIT", "main": "dist/index.js", @@ -9,9 +9,7 @@ "copy": "yarn run mkdir && cp src/utils/ScalarsClient.mustache dist/templates/ScalarsClient.mustache", "build": "rimraf dist && tsc && rollup -c && rimraf dist/dts && yarn run copy", "test": "yarn build && node dist/sync.js && jest --detectOpenHandles --forceExit --testTimeout=540000", - "jest": "jest --testTimeout=540000 --runInBand", - "prepublish": "yarn build", - "postinstall": "yarn build" + "jest": "jest --testTimeout=540000 --runInBand" }, "files": [ "dist" @@ -30,7 +28,6 @@ "@rollup/plugin-typescript": "^8.2.1", "@types/inquirer": "^7.3.3", "@types/inquirer-fuzzy-path": "^2.3.2", - "@scalars/cli": "file:./dist/dts", "@types/jest": "^26.0.24", "@types/mustache": "^4.1.1", "@types/rollup__plugin-virtual": "^2.0.1", @@ -46,13 +43,14 @@ "rollup-plugin-terser": "^7.0.2", "ts-jest": "^27.0.3", "tslib": "^2.3.0", + "rollup": "^1.32.1", "typescript": "^4.3.4", "yargs": "^17.0.1" }, "bin": { "scalars": "dist/sync.js" }, - "repository": "https://gitlab.com/scalars/cli", + "repository": "https://github.com/scalars/cli", "dependencies": { "@apollo/client": "^3.3.21", "@graphql-codegen/cli": "^2.0.1", From c450a424cce0f7ee1f6aaaae932b0ae8679cd733 Mon Sep 17 00:00:00 2001 From: Carlos Guadir Date: Wed, 8 Sep 2021 09:22:20 -0500 Subject: [PATCH 3/8] Fixes --- package.json | 2 +- rollup.config.js | 2 +- src/client/ScalarsClient.ts | 19 ------------------- src/client/index.ts | 1 - src/client/services/MutationsService.ts | 3 --- src/client/services/QueriesService.ts | 3 --- src/client/services/Service.ts | 1 - src/client/services/index.ts | 2 -- src/index.ts | 1 - tsconfig.json | 2 +- 10 files changed, 3 insertions(+), 33 deletions(-) delete mode 100644 src/client/ScalarsClient.ts delete mode 100644 src/client/index.ts delete mode 100644 src/client/services/MutationsService.ts delete mode 100644 src/client/services/QueriesService.ts delete mode 100644 src/client/services/Service.ts delete mode 100644 src/client/services/index.ts delete mode 100644 src/index.ts diff --git a/package.json b/package.json index c14e9e4..5682ad5 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "scripts": { "mkdir": "mkdir -p dist/templates", "copy": "yarn run mkdir && cp src/utils/ScalarsClient.mustache dist/templates/ScalarsClient.mustache", - "build": "rimraf dist && tsc && rollup -c && rimraf dist/dts && yarn run copy", + "build": "rimraf dist && rollup -c && rimraf dist/dts && yarn run copy", "test": "yarn build && node dist/sync.js && jest --detectOpenHandles --forceExit --testTimeout=540000", "jest": "jest --testTimeout=540000 --runInBand" }, diff --git a/rollup.config.js b/rollup.config.js index 14c291a..a7b6f91 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -18,6 +18,6 @@ export default [ { input: './dist/dts/index.d.ts', output: [{ file: 'dist/index.d.ts', format: 'es' }], - plugins: [dts()] + plugins: [ dts() ] } ] diff --git a/src/client/ScalarsClient.ts b/src/client/ScalarsClient.ts deleted file mode 100644 index d257a63..0000000 --- a/src/client/ScalarsClient.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { MutationsService, QueriesService } from './services' - -export class ScalarsClient { - private readonly queriesService: QueriesService - private readonly mutationsService: MutationsService - - constructor() { - this.queriesService = new QueriesService() - this.mutationsService = new MutationsService() - } - - get query () { - return this.queriesService - } - - get mutation () { - return this.mutationsService - } -} diff --git a/src/client/index.ts b/src/client/index.ts deleted file mode 100644 index a2aed8c..0000000 --- a/src/client/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './ScalarsClient' diff --git a/src/client/services/MutationsService.ts b/src/client/services/MutationsService.ts deleted file mode 100644 index b0d8797..0000000 --- a/src/client/services/MutationsService.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { Service } from './Service' - -export class MutationsService extends Service {} diff --git a/src/client/services/QueriesService.ts b/src/client/services/QueriesService.ts deleted file mode 100644 index 74cefe3..0000000 --- a/src/client/services/QueriesService.ts +++ /dev/null @@ -1,3 +0,0 @@ -class Service { } - -export class QueriesService extends Service {} diff --git a/src/client/services/Service.ts b/src/client/services/Service.ts deleted file mode 100644 index a2cd213..0000000 --- a/src/client/services/Service.ts +++ /dev/null @@ -1 +0,0 @@ -export abstract class Service { } diff --git a/src/client/services/index.ts b/src/client/services/index.ts deleted file mode 100644 index d49a2ef..0000000 --- a/src/client/services/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './MutationsService' -export * from './QueriesService' diff --git a/src/index.ts b/src/index.ts deleted file mode 100644 index 83dae76..0000000 --- a/src/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './client' diff --git a/tsconfig.json b/tsconfig.json index 6e44423..c1a48ad 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,6 +14,6 @@ "rootDir": "src", }, "include": ["./src/**/*.ts"], - "exclude": [ ".dist/**/*.ts" ] + "exclude": [ ".dist/**/*.ts", "./src/__test__/**/*", "./src/tests/**/*" ] } From b2b7cc4142c9b1981b55e1f8e08113c8260987da Mon Sep 17 00:00:00 2001 From: LuisDanilo Date: Wed, 8 Sep 2021 09:41:57 -0500 Subject: [PATCH 4/8] final fixes on build --- package.json | 5 +++-- rollup.config.js | 10 +++++----- tsconfig.json | 3 +-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/package.json b/package.json index 5682ad5..d4931bd 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,11 @@ { "name": "@scalars/cli", - "version": "1.2.237", + "version": "1.2.239", "description": "Client for scalars application", "license": "MIT", "main": "dist/index.js", "scripts": { + "prepublish": "yarn build", "mkdir": "mkdir -p dist/templates", "copy": "yarn run mkdir && cp src/utils/ScalarsClient.mustache dist/templates/ScalarsClient.mustache", "build": "rimraf dist && rollup -c && rimraf dist/dts && yarn run copy", @@ -44,7 +45,6 @@ "ts-jest": "^27.0.3", "tslib": "^2.3.0", "rollup": "^1.32.1", - "typescript": "^4.3.4", "yargs": "^17.0.1" }, "bin": { @@ -52,6 +52,7 @@ }, "repository": "https://github.com/scalars/cli", "dependencies": { + "typescript": "^4.3.4", "@apollo/client": "^3.3.21", "@graphql-codegen/cli": "^2.0.1", "@graphql-codegen/introspection": "^2.0.0", diff --git a/rollup.config.js b/rollup.config.js index a7b6f91..9085cea 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -15,9 +15,9 @@ export default [ plugins: [typescript(), terser()], external: ['dotenv', 'path', 'yargs', 'inquirer', '@graphql-codegen/cli', 'fs', 'mustache', 'tsc-prog', 'inquirer-fuzzy-path'] }, - { - input: './dist/dts/index.d.ts', - output: [{ file: 'dist/index.d.ts', format: 'es' }], - plugins: [ dts() ] - } + // { + // input: './dist/dts/index.d.ts', + // output: [{ file: 'dist/index.d.ts', format: 'es' }], + // plugins: [ dts() ] + // } ] diff --git a/tsconfig.json b/tsconfig.json index c1a48ad..a63cb05 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -10,8 +10,7 @@ "outDir": "./dist", "declaration": true, "declarationDir": "./dist/dts", - "emitDeclarationOnly": true, - "rootDir": "src", + "emitDeclarationOnly": true }, "include": ["./src/**/*.ts"], "exclude": [ ".dist/**/*.ts", "./src/__test__/**/*", "./src/tests/**/*" ] From 40e2b97411a2493831966bdf897dcabd2ddf9b66 Mon Sep 17 00:00:00 2001 From: Carlos Guadir Date: Tue, 7 Sep 2021 22:43:58 -0500 Subject: [PATCH 5/8] Refactor build --- .eslintrc | 60 +- .gitignore | 2 + jest.config.js | 3 - package.json | 29 +- rollup.config.js | 6 - src/__test__/client.test.ts | 519 ------------------ src/client/ScalarsClient.ts | 19 - src/client/index.ts | 1 - src/client/services/MutationsService.ts | 5 - src/client/services/QueriesService.ts | 110 ---- src/client/services/Service.ts | 5 - src/client/services/index.ts | 2 - src/index.ts | 1 - src/scripts/postinstall.ts | 1 - src/scripts/sync.ts | 105 ++-- src/tests/cli/env.test | 1 + src/tests/cli/introspection.spec.test.ts | 43 ++ .../queries}/client.seeds.ts | 0 src/tests/queries/client.test.ts | 340 ++++++++++++ src/utils/ScalarsClient.mustache | 19 +- src/utils/ScalarsClientManager.mustache | 2 +- src/utils/Service.mustache | 2 +- src/utils/interfaces.ts | 1 - src/utils/introspect.ts | 104 ++-- src/utils/template.mustache | 2 +- tsconfig.json | 29 +- 26 files changed, 538 insertions(+), 873 deletions(-) delete mode 100644 src/__test__/client.test.ts delete mode 100644 src/client/ScalarsClient.ts delete mode 100644 src/client/index.ts delete mode 100644 src/client/services/MutationsService.ts delete mode 100644 src/client/services/QueriesService.ts delete mode 100644 src/client/services/Service.ts delete mode 100644 src/client/services/index.ts delete mode 100644 src/index.ts delete mode 100644 src/scripts/postinstall.ts create mode 100644 src/tests/cli/env.test create mode 100644 src/tests/cli/introspection.spec.test.ts rename src/{__test__ => tests/queries}/client.seeds.ts (100%) create mode 100644 src/tests/queries/client.test.ts diff --git a/.eslintrc b/.eslintrc index 7d30070..7693103 100644 --- a/.eslintrc +++ b/.eslintrc @@ -5,33 +5,63 @@ "plugin:@typescript-eslint/recommended" ], "parser": "@typescript-eslint/parser", - "plugins": ["@typescript-eslint"], + "plugins": [ + "@typescript-eslint", + "simple-import-sort" + ], "parserOptions": { - "project": "tsconfig.json" + "project": "./tsconfig.json" }, "root": true, + "ignorePatterns": [ "**/*.test.ts"], "rules": { + "simple-import-sort/imports": "error", + "simple-import-sort/exports": "error", + "object-curly-newline": ["error", { + "ImportDeclaration": { + "multiline": true + }, + "ExportDeclaration": { + "multiline": true, + "minProperties": 3 + } + }], + "no-useless-escape": "off", + "no-console": [ "error", { "allow": [ "error", "info" ] } ], + "no-tabs": "off", + "no-mixed-spaces-and-tabs": "error", + "semi": [ 2, "never" ], + "@typescript-eslint/no-unused-vars": [ "error", { "argsIgnorePattern": "^_" } ], "@typescript-eslint/restrict-plus-operands": "error", + "@typescript-eslint/ban-ts-ignore": "off", + "@typescript-eslint/ban-types": "off", "@typescript-eslint/no-inferrable-types": "off", - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/explicit-module-boundary-types": "off", - "@typescript-eslint/indent": ["error", 4, { - "FunctionDeclaration": {"parameters": "first"}, - "FunctionExpression": {"parameters": "first"} - }], - "@typescript-eslint/no-use-before-define": ["error", { + "@typescript-eslint/no-explicit-any": "warn", + "@typescript-eslint/indent": [ "error", 4, { + "FunctionDeclaration": { "parameters": "first" }, + "FunctionExpression": { "parameters": "first" } + } ], + "@typescript-eslint/type-annotation-spacing": "error", + "@typescript-eslint/no-use-before-define": [ "error", { "variables": true, "functions": true - }], - "no-case-declarations": "off", - "quotes": ["error", "single", { + } ], + "quotes": [ "error", "single", { "allowTemplateLiterals": true - }], - "semi": [ "error", "never" ], - "camelcase": "off", + } ], + "array-bracket-spacing": [ "error", "always" ], + "comma-spacing": [ "error", { "before": false, "after": true } ], "object-curly-spacing": [ "error", "always" ], + "space-unary-ops": [ + 2, { + "words": true, + "nonwords": true + } + ], "block-spacing": [ "error", "always" ], "space-in-parens": [ "error", "always" ], + "max-lines": [ "error", { "max": 500, "skipBlankLines": true, "skipComments": true } ], + "max-lines-per-function": [ "error", 70 ], "space-infix-ops": [ "error", { "int32Hint": true } ] } } diff --git a/.gitignore b/.gitignore index 2305373..86f1593 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ yarn.lock yarn-error.log package-lock.json +test-report.xml +tsconfig.tsbuildinfo node_modules dist .env.dev diff --git a/jest.config.js b/jest.config.js index 793d9f2..ff5fad2 100644 --- a/jest.config.js +++ b/jest.config.js @@ -5,9 +5,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testResultsProcessor: "jest-sonar-reporter", - // testMatch: [ - // `src/__tests__/**/*.+(spec|test).+(ts|js)` - // ], transform: { '^.+\\.ts$': 'ts-jest' }, diff --git a/package.json b/package.json index 0533580..920336b 100644 --- a/package.json +++ b/package.json @@ -1,14 +1,14 @@ { - "name": "@juaji/scalars-cli", - "version": "1.2.22", - "description": "Client for scalars APIs", - "author": "LuisDanilo ", + "name": "@scalars/cli", + "version": "1.2.3", + "description": "Client for scalars application", "license": "MIT", "main": "dist/index.js", "scripts": { + "prepublish": "yarn build", "mkdir": "mkdir -p dist/templates", "copy": "yarn run mkdir && cp src/utils/ScalarsClient.mustache dist/templates/ScalarsClient.mustache", - "build": "rimraf dist && tsc && rollup -c && rimraf dist/dts && yarn run copy", + "build": "rimraf dist && rollup -c && rimraf dist/dts && yarn run copy", "test": "yarn build && node dist/sync.js && jest --detectOpenHandles --forceExit --testTimeout=540000", "jest": "jest --testTimeout=540000 --runInBand" }, @@ -19,18 +19,24 @@ "keywords": [ "scalars", "sdk", - "scalars-cli", + "cli", + "graphql", + "serverless", + "baas", "madrov" ], "devDependencies": { "@rollup/plugin-typescript": "^8.2.1", "@types/inquirer": "^7.3.3", + "@types/inquirer-fuzzy-path": "^2.3.2", "@types/jest": "^26.0.24", "@types/mustache": "^4.1.1", "@types/rollup__plugin-virtual": "^2.0.1", "@typescript-eslint/eslint-plugin": "^4.28.1", "@typescript-eslint/parser": "^4.28.1", + "child-process": "^1.0.2", "eslint": "^7.29.0", + "eslint-plugin-simple-import-sort": "^7.0.0", "jest": "^27.0.6", "jest-sonar-reporter": "^2.0.0", "rimraf": "^3.0.2", @@ -38,13 +44,15 @@ "rollup-plugin-terser": "^7.0.2", "ts-jest": "^27.0.3", "tslib": "^2.3.0", - "typescript": "^4.3.4" + "rollup": "^1.32.1", + "yargs": "^17.0.1" }, "bin": { "scalars": "dist/sync.js" }, - "repository": "https://gitlab.com/LuisDanilo/scalars-cli", + "repository": "https://github.com/scalars/cli", "dependencies": { + "typescript": "^4.3.4", "@apollo/client": "^3.3.21", "@graphql-codegen/cli": "^2.0.1", "@graphql-codegen/introspection": "^2.0.0", @@ -53,13 +61,12 @@ "@types/node-fetch": "^2.5.11", "dotenv": "^10.0.0", "graphql": "^15.5.1", + "graphql-tag": "^2.12.5", "inquirer": "^8.1.2", "inquirer-fuzzy-path": "^2.3.0", "mustache": "^4.2.0", "node-fetch": "^2.6.1", "react": "^17.0.2", - "tsc-prog": "^2.2.1", - "yargs": "^17.0.1", - "graphql-tag": "^2.12.5" + "tsc-prog": "^2.2.1" } } diff --git a/rollup.config.js b/rollup.config.js index 14c291a..d8e4004 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -1,5 +1,4 @@ import typescript from '@rollup/plugin-typescript' -import dts from 'rollup-plugin-dts' import { terser } from 'rollup-plugin-terser' export default [ @@ -14,10 +13,5 @@ export default [ ], plugins: [typescript(), terser()], external: ['dotenv', 'path', 'yargs', 'inquirer', '@graphql-codegen/cli', 'fs', 'mustache', 'tsc-prog', 'inquirer-fuzzy-path'] - }, - { - input: './dist/dts/index.d.ts', - output: [{ file: 'dist/index.d.ts', format: 'es' }], - plugins: [dts()] } ] diff --git a/src/__test__/client.test.ts b/src/__test__/client.test.ts deleted file mode 100644 index c54512e..0000000 --- a/src/__test__/client.test.ts +++ /dev/null @@ -1,519 +0,0 @@ -import { IFaq, IProfile, IRegistration, ProfileSelect, ScalarsClient } from '../../dist/index' -import { faqSeeds, registrationSeeds } from './client.seeds' - -const client: ScalarsClient = new ScalarsClient() - -const idRegex: RegExp = new RegExp( `[0-9a-fA-F]{16}` ) -const dateRegex: RegExp = new RegExp( `[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T(2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]\\.[0-9]{3}Z` ) -const emailRegex: RegExp = new RegExp( `[a-zA-Z]+@[a-zA-Z]+.+` ) -const { objectContaining, stringContaining, anything, stringMatching, arrayContaining } = expect -const { floor, random } = Math - -describe( `Registration`, () => { - const { createRegistration, updateRegistration } = registrationSeeds - describe( `Should read multiple and single registrations`, () => { - let registrationId: string = '' - test( `Should read registrations`, ( done ) => { - client.query - .registrations( { - select: { id: true } - } ) - .then( ( res: Array ) => { - expect( res ).toEqual( arrayContaining( [objectContaining( { - id: stringMatching( idRegex ), - } )] ) ) - registrationId = res[floor( random() * res.length )].id || '' - done() - } ) - .catch( ( err: unknown ) => { - console.log( err ) - } ) - } ) - test( `Should read registration`, ( done ) => { - expect( registrationId ).toEqual( stringMatching( idRegex ) ) - client.query - .registration( { - select: { email: true, name: true, createdAt: true, updatedAt: true, linkedin: true }, - where: { id: registrationId } - } ) - .then( ( res: IRegistration ) => { - expect( res ).toEqual( objectContaining( { - email: stringMatching( emailRegex ), - name: stringContaining( '' ), - createdAt: stringMatching( dateRegex ), - updatedAt: stringMatching( dateRegex ), - linkedin: stringContaining( '' ) - } ) ) - done() - } ) - .catch( ( err: unknown ) => console.log( err ) ) - } ) - } ) - describe( `Should create, update and delete registration`, () => { - let registrationId: string = '' - test( `Should create registration`, ( done ) => { - client.mutation - .createRegistration( { - select: { id: true }, - data: { - email: createRegistration.email, - name: createRegistration.name, - linkedin: createRegistration.linkedin - } - } ) - .then( ( res: IRegistration ) => { - expect( res ).toEqual( objectContaining( { - id: stringMatching( idRegex ) - } ) ) - registrationId = res.id || '' - done() - } ) - .catch( ( err: unknown ) => console.log( err ) ) - } ) - test( `Should update registration`, ( done ) => { - expect( registrationId ).toEqual( stringMatching( idRegex ) ) - client.mutation - .updateRegistration( { - select: { id: true, name: true, email: true, linkedin: true, createdAt: true, updatedAt: true }, - where: { id: registrationId }, - data: { email: updateRegistration.email, name: updateRegistration.name } - } ) - .then( ( res: IRegistration ) => { - expect( res ).toEqual( objectContaining( { - id: stringContaining( registrationId ), - name: stringContaining( updateRegistration.name ), - email: stringContaining( updateRegistration.email ), - linkedin: stringContaining( createRegistration.linkedin ), - createdAt: stringMatching( dateRegex ), - updatedAt: stringMatching( dateRegex ) - } ) ) - done() - } ) - .catch( ( err:unknown ) => console.log( err ) ) - } ) - test( `Should delete registration`, ( done ) => { - expect( registrationId ).toEqual( stringMatching( idRegex ) ) - client.mutation - .deleteRegistration( { - select: { id: true, name: true, email: true, createdAt: true, linkedin: true, updatedAt: true }, - where: { id: registrationId } - } ) - .then( ( res: IRegistration ) => { - expect( res ).toEqual( objectContaining( { - id: stringContaining( registrationId ), - name: stringContaining( updateRegistration.name ), - email: stringContaining( updateRegistration.email ), - createdAt: stringMatching( dateRegex ), - linkedin: stringContaining( createRegistration.linkedin ), - updatedAt: stringMatching( dateRegex ) - } ) ) - done() - } ) - .catch( ( err:unknown ) => console.log( err ) ) - } ) - } ) -} ) - -describe( `Faq`, () => { - const { createFaq, updateFaq } = faqSeeds - describe( `Should read multiple and single faqs`, () => { - let faqId: string = '' - test( `Should read faqs`, ( done ) => { - client.query - .faqs( { - select: { id: true } - } ) - .then( ( res: Array ) => { - expect( res ).toEqual( arrayContaining( [objectContaining( { - id: stringMatching( idRegex ) - } )] ) ) - faqId = res[floor( random() * res.length )].id || '' - done() - } ) - .catch( ( err: unknown ) => { - console.log( err ) - } ) - } ) - test( `Should read faq`, ( done ) => { - expect( faqId ).toEqual( stringMatching( idRegex ) ) - client.query - .faq( { - select: { answer: true, question: true, createdAt: true, updatedAt: true }, - where: { id: faqId } - } ) - .then( ( res: IFaq ) => { - expect( res ).toEqual( objectContaining( { - answer: stringContaining( '' ), - question: stringContaining( '' ), - createdAt: stringMatching( dateRegex ), - updatedAt: stringMatching( dateRegex ) - } ) ) - done() - } ) - .catch( ( err: unknown ) => console.log( err ) ) - } ) - } ) - describe( `Should create, update and delete faq`, () => { - let faqId: string = '' - test( `Should create faq`, ( done ) => { - client.mutation - .createFaq( { - select: { - id: true - }, - data: { - question: createFaq.question, - answer: createFaq.answer - } - } ) - .then ( ( res: IFaq ) => { - expect( res ).toEqual( objectContaining( { - id: stringMatching( idRegex ) - } ) ) - faqId = res.id || '' - done() - } ) - .catch( ( err:unknown ) => console.log( err ) ) - } ) - test( `Should update faq`, ( done ) => { - expect( faqId ).toEqual( stringMatching( idRegex ) ) - client.mutation - .updateFaq( { - select: { id: true, question: true, answer: true, createdAt: true, updatedAt: true }, - where: { id: faqId }, - data: { question: updateFaq.question } - } ) - .then( ( res: IFaq ) => { - expect( res ).toEqual( objectContaining( { - id: stringContaining( faqId ), - question: stringContaining( updateFaq.question ), - answer: stringContaining( createFaq.answer ), - createdAt: stringMatching( dateRegex ), - updatedAt: stringMatching( dateRegex ) - } ) ) - done() - } ) - .catch( ( err: unknown ) => console.log( err ) ) - } ) - test( `Should delete faq`, ( done ) => { - expect( faqId ).toEqual( stringMatching( idRegex ) ) - client.mutation - .deleteFaq( { - select: { id: true, answer: true, question: true, createdAt: true, updatedAt: true }, - where: { id: faqId } - } ) - .then( ( res: IFaq ) => { - expect( res ).toEqual( objectContaining( { - id: stringContaining( faqId ), - question: stringContaining( updateFaq.question ), - answer: stringContaining( createFaq.answer ), - createdAt: stringMatching( dateRegex ), - updatedAt: stringMatching( dateRegex ) - } ) ) - done() - } ) - .catch( ( err:unknown ) => console.log( err ) ) - } ) - } ) -} ) - -describe( `Answers`, () => { - test( `Should read answer`, ( done ) => { - done() - } ) - test( `Should create answer`, ( done ) => { - done() - } ) - test( `Should update answer`, ( done ) => { - done() - } ) - test( `Should delete answer`, ( done ) => { - done() - } ) -} ) - -describe( `Skill`, () => { - test( `Should read skill`, ( done )=>{ - done() - } ) - test( `Should create skill`, ( done ) => { - done() - } ) - test( `Should update skill`, ( done ) => { - done() - } ) - test( `Should delete skill`, ( done ) => { - done() - } ) -} ) - -describe( `Interest`, () => { - test( `Should read interest`, ( done ) => { - done() - } ) - test( `Should create interest`, ( done ) => { - done() - } ) - test( `Should update interest`, ( done ) => { - done() - } ) - test( `Should delete interest`, ( done ) => { - done() - } ) -} ) - -describe( `Profile`, () => { - test( `Should read profile`, ( done ) => { - // 1st - // client - // .doQuery( - // `query profile($where: ProfileWhereUniqueInput!) { profile(where: $where) { id } }`, - // { where: { email: 'luis@madrov.com' } } - // ) - // .then( ( res: Record<'profile', any> ) => { - // console.log( res.profile ) - // } ) - // .catch( ( err: unknown ) => { - // console.log( err ) - // } ) - // .finally( done ) - // 2nd - const profileSelect: ProfileSelect = { - id: true, email: true, description: true, phone: true, - sentConnections: { - id: true, createdAt: true, updatedAt: true, status: true, - sender: { - id: true, email: true, interests: true, - user: { - name: true, id: true, createdAt: true - } - }, - receiver: { - id: true, email: true, interests: true, - user: { - name: true, id: true, createdAt: true, - } - } - }, - founder_projects: { - name: true, - founders: { - email: true - }, - requests: { - id: true, status: true, createdAt: true, - invitee: { - email: true - }, - inviter: { - email: true - }, - project: { - name: true - } - } - }, - receivedConnections: { - id: true, createdAt: true, updatedAt: true, status: true, - sender: { - id: true, email: true, interests: true, - user: { - name: true, id: true, createdAt: true - } - }, - receiver: { - id: true, email: true, interests: true, - user: { - name: true, id: true, createdAt: true - } - } - }, - user: { username: true } - } - client.query - .profiles( { - select: profileSelect, - where: { user: { username: '+573145463091' } } - } ) - .then ( ( res: Array ) => { - console.log( res ) - done() - // expect( res ).toEqual( expect.objectContaining( { - // id: expect.stringMatching( idRegex ), - // email: expect.stringContaining( `andres` ), - // description: expect.stringContaining( `Desarrollador Backend` ), - // phone: null, - // sentConnections: expect.arrayContaining( [expect.objectContaining( { - // id: expect.stringMatching( idRegex ), - // createdAt: expect.stringMatching( dateRegex ), - // updatedAt: expect.stringMatching( dateRegex ), - // status: expect.anything(), - // sender: expect.objectContaining( { - // id: expect.stringMatching( idRegex ), - // email: expect.stringMatching( emailRegex ), - // user: expect.objectContaining( { - // name: expect.anything(), - // id: expect.stringMatching( idRegex ), - // createdAt: expect.stringMatching( dateRegex ), - // } ) - // } ), - // receiver: expect.objectContaining( { - // id: expect.stringMatching( idRegex ), - // email: expect.stringMatching( emailRegex ), - // user: expect.objectContaining( { - // name: expect.anything(), - // id: expect.stringMatching( idRegex ), - // createdAt: expect.stringMatching( dateRegex ) - // } ) - // } ) - // } )] ), - // founder_projects: expect.arrayContaining( [expect.objectContaining( { - // name: expect.anything(), - // founders: expect.arrayContaining( [expect.objectContaining( { - // email: expect.stringMatching( emailRegex ) - // } )] ), - // requests: expect.arrayContaining( [expect.objectContaining( { - // id: expect.stringMatching( idRegex ), - // status: expect.anything(), - // createdAt: expect.stringMatching( dateRegex ), - // invitee: expect.objectContaining( { - // email: expect.stringMatching( emailRegex ) - // } ), - // inviter: expect.objectContaining( { - // email: expect.stringMatching( emailRegex ) - // } ), - // project: expect.objectContaining( { - // name: expect.anything() - // } ) - // } )] ) - // } )] ), - // // receivedConnection: expect.arrayContaining( [expect.objectContaining( { - // // id: expect.stringMatching( idRegex ), - // // createdAt: expect.stringMatching( dateRegex ), - // // updatedAt: expect.stringMatching( dateRegex ), - // // status: expect.anything(), - // // sender: expect.objectContaining( { - // // id: expect.stringMatching( idRegex ), - // // email: expect.stringMatching( emailRegex ), - // // user: expect.objectContaining( { - // // name: expect.anything(), - // // id: expect.stringMatching( idRegex ), - // // createdAt: expect.stringMatching( dateRegex ), - // // } ) - // // } ), - // // receiver: expect.objectContaining( { - // // id: expect.stringMatching( idRegex ), - // // email: expect.stringMatching( emailRegex ), - // // user: expect.objectContaining( { - // // name: expect.anything(), - // // id: expect.stringMatching( idRegex ), - // // createdAt: expect.stringMatching( dateRegex ) - // // } ) - // // } ) - // // } )] ) - // } ) ) - } ) - .catch( ( err: unknown ) => { - console.log( err ) - } ) - } ) - test( `Should create profile`, ( done ) => { - done() - } ) - test( `Should update profile`, ( done ) => { - done() - } ) - test( `Should delete profile`, ( done ) => { - done() - } ) -} ) - -describe( `Chat`, () => { - test( `Should read chat`, ( done ) => { - done() - } ) - test( `Should create chat`, ( done ) => { - done() - } ) - test( `Should update chat`, ( done ) => { - done() - } ) - test( `Should delete chat`, ( done ) => { - done() - } ) -} ) - -describe( `Message`, () => { - test( `Should read message`, ( done ) => { - done() - } ) - test( `Should create message`, ( done ) => { - done() - } ) - test( `Should update message`, ( done ) => { - done() - } ) - test( `Should delete message`, ( done ) => { - done() - } ) -} ) - -describe( `Connection`, () => { - test( `Should read connection`, ( done ) => { - done() - } ) - test( `Should create connection`, ( done ) => { - done() - } ) - test( `Should update connection`, ( done ) => { - done() - } ) - test( `Should delete connection`, ( done ) => { - done() - } ) -} ) - -describe( `Project`, () => { - test( `Should read project`, ( done ) => { - done() - } ) - test( `Should create project`, ( done ) => { - done() - } ) - test( `Should update project`, ( done ) => { - done() - } ) - test( `Should delete project`, ( done ) => { - done() - } ) -} ) - -describe( `Request`, () => { - test( `Should read request`, ( done ) => { - done() - } ) - test( `Should create request`, ( done ) => { - done() - } ) - test( `Should update request`, ( done ) => { - done() - } ) - test( `Should delete request`, ( done ) => { - done() - } ) -} ) - -describe( `Comment`, () => { - test( `Should read comment`, ( done ) => { - done() - } ) - test( `Should create comment`, ( done ) => { - done() - } ) - test( `Should update comment`, ( done ) => { - done() - } ) - test( `Should delete comment`, ( done ) => { - done() - } ) -} ) diff --git a/src/client/ScalarsClient.ts b/src/client/ScalarsClient.ts deleted file mode 100644 index d257a63..0000000 --- a/src/client/ScalarsClient.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { MutationsService, QueriesService } from './services' - -export class ScalarsClient { - private readonly queriesService: QueriesService - private readonly mutationsService: MutationsService - - constructor() { - this.queriesService = new QueriesService() - this.mutationsService = new MutationsService() - } - - get query () { - return this.queriesService - } - - get mutation () { - return this.mutationsService - } -} diff --git a/src/client/index.ts b/src/client/index.ts deleted file mode 100644 index a2aed8c..0000000 --- a/src/client/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './ScalarsClient' diff --git a/src/client/services/MutationsService.ts b/src/client/services/MutationsService.ts deleted file mode 100644 index b60a2cb..0000000 --- a/src/client/services/MutationsService.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { Service } from './Service' - -export class MutationsService extends Service { - -} diff --git a/src/client/services/QueriesService.ts b/src/client/services/QueriesService.ts deleted file mode 100644 index e5f64d9..0000000 --- a/src/client/services/QueriesService.ts +++ /dev/null @@ -1,110 +0,0 @@ -class Service { -} - -export class QueriesService extends Service { - // getAnswer ( where: Record, ) { - // console.log( 'ho' ) - // } - // getAnswers () { - // } - // getAppclient () { - // } - // getAppclients () { - // } - // getAssetsconfig () { - // } - // getAssetsconfigs () { - // } - // getAuthcodegrant () { - // } - // getAuthcodegrants () { - // } - // getAuthrole () { - // } - // getAuthroles () { - // } - // getAuthsession () { - // } - // getAuthsessions () { - // } - // getAuthuser () { - // } - // getAuthusers () { - // } - // getChat () { - // } - // getChats () { - // } - // getComment () { - // } - // getComments () { - // } - // getConnection () { - // } - // getConnections () { - // } - // getCountry () { - // } - // getCountries () { - // } - // getDatapermission () { - // } - // getDatapermissions () { - // } - // getDocumentfile () { - // } - // getDocumentfiles () { - // } - // getFaq () { - // } - // getFaqs () { - // } - // getImagefile () { - // } - // getImagefiles () { - // } - // getInterest () { - // } - // getInterests () { - // } - // getMessage () { - // } - // getMessages () { - // } - // getMimetype () { - // } - // getMimetypes () { - // } - // getProfile () { - // } - // getProfiles () { - // } - // getProject () { - // } - // getProjects () { - // } - // getRegistration () { - // } - // getRegistrations () { - // } - // getRequest () { - // } - // getRequests () { - // } - // getSkill () { - // } - // getSkills () { - // } - // getSoundfile () { - // } - // getSoundfiles () { - // } - // getTrigger () { - // } - // getTriggers () { - // } - // getVideofile () { - // } - // getVideofiles () { - // } -} diff --git a/src/client/services/Service.ts b/src/client/services/Service.ts deleted file mode 100644 index 5016a87..0000000 --- a/src/client/services/Service.ts +++ /dev/null @@ -1,5 +0,0 @@ -export abstract class Service { - // protected async doQuery ( query: string, variables: V ): Promise { - // - // } -} diff --git a/src/client/services/index.ts b/src/client/services/index.ts deleted file mode 100644 index d39d996..0000000 --- a/src/client/services/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './QueriesService' -export * from './MutationsService' diff --git a/src/index.ts b/src/index.ts deleted file mode 100644 index 83dae76..0000000 --- a/src/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './client' diff --git a/src/scripts/postinstall.ts b/src/scripts/postinstall.ts deleted file mode 100644 index 9ddc1c2..0000000 --- a/src/scripts/postinstall.ts +++ /dev/null @@ -1 +0,0 @@ -console.log( 'Maldita sea' ) diff --git a/src/scripts/sync.ts b/src/scripts/sync.ts index 28e72e0..2c466ee 100644 --- a/src/scripts/sync.ts +++ b/src/scripts/sync.ts @@ -1,28 +1,36 @@ -import { introspect } from '../utils/introspect' import { config } from 'dotenv' -import { join, resolve } from 'path' -import yargs from 'yargs' import inquirer from 'inquirer' -import * as fuzzyPath from 'inquirer-fuzzy-path' -// Inquirer setup +import fuzzyPath from 'inquirer-fuzzy-path' +import { join } from 'path' +import yargs from 'yargs' + +import { introspect } from '../utils/introspect' inquirer.registerPrompt( 'path', fuzzyPath ) +const succesMessage: string = ` +Introspection success ! + Enjoy your experience using Scalars + Happy codding!! +== Madrov team️ == +` + /** * Function that starts introspection * @param endpoint Endpoint to introspect - * @param clientId Client id to authorize introspection * @param clientPath Path where ScalarsClient.ts will be generated * @param soft Make soft introspection */ -const sync = ( endpoint: string, clientId: string, clientPath: string, soft: boolean ) => { +const sync = ( endpoint: string, clientPath: string, soft: boolean ) => { introspect( { endpoint, - clientId, clientPath, soft } ).then( () => { - // console.clear() - console.info( `Introspection success!\n\tEnjoy your experience using Scalars\n\tHappy codding!!\n== Madrov team️ ==` ) + console.info( succesMessage ) + process.exit( 0 ) + } ).catch( error => { + console.info( error ) + process.exit( - 1 ) } ) } @@ -31,57 +39,39 @@ const sync = ( endpoint: string, clientId: string, clientPath: string, soft: boo * @param interactive Flag to enable command line menu * @param endpoint Endpoint recovered from command line option "-e or --endpoint". * @param authorization Authorization recovered from command line option "-a or --authorization". + * @param env * @param prod Flag to use .env.prod file as introspection values, otherwise .env.dev is taken by default. + * @param soft */ -const loadEnvsAndIntrospect = ( interactive: boolean, endpoint: string | null, authorization: string | null, prod: boolean, soft: boolean ) => { - // endpoint final a usar +const loadEnvsAndIntrospect = ( + interactive: boolean, + endpoint: string | null, + authorization: string | null, + env: string | null, + prod: boolean, + soft: boolean +) => { let currentEndpoint: string | null = endpoint - // authorization final a usar, un string "client_id xxxxxx" oo un string jwt - let currentAuthorization: string | null = authorization - // Para cuando el menu esta habilitado, ruta por defecto en donde se exporta ScalarsClient.ts let clientPath: string = __dirname - // Bandera para errores varios - const { error, parsed } = config( { path: join( process.cwd(), `${prod ? '.env.prod' : '.env.dev'}` ) } ) - if ( !error && parsed ) { - // Environment variables loaded successfully - currentEndpoint = ( endpoint || parsed.SCALARS_ENDPOINT ) as string - currentAuthorization = ( authorization || parsed.SCALARS_CLIENT_ID ) as string + if ( env ) { + const { error, parsed } = config( { path: join( process.cwd(), `${env ? env : '.env'}` ) } ) + if ( ! error && parsed ) { + currentEndpoint = parsed.SCALARS_ENDPOINT as string + } } else { - console.info( `DOTENV ERROR: Couldn't load ${join( process.cwd(), `${prod ? '.env.prod' : '.env.dev'}` )}` ) - return + currentEndpoint = ( endpoint || process.env.SCALARS_ENDPOINT ) as string } - if ( !interactive ) { - // Have to make auto introspection - if ( currentEndpoint && currentAuthorization ) { - // endpoint and auth already configured, supplied through command line options - console.info( `Introspection with endpoint ${currentEndpoint}` ) - console.info( `Using client id ${currentAuthorization}` ) - sync( currentEndpoint as string, currentAuthorization as string, __dirname, soft ) - } else { - console.info( 'DOTENV ERROR: Environment variables loaded, but SCALARS_ENDPOINT or SCALARS_CLIENT_ID were not found' ) - return - } + if ( ! interactive && currentEndpoint ) { + console.info( `Start introspection ${currentEndpoint}` ) + sync( currentEndpoint as string, __dirname, soft ) } else { - // Have to make assisted introspection (with command line menu) inquirer.prompt( [ - { - type: 'confirm', - name: 'defaultEnvs', - message: `\tENDPOINT=${currentEndpoint}\n\tAUTHORIZATION=${currentAuthorization}\n♦♣♥♠ Are these your cards? (loaded from ${prod ? '.env.prod' : '.env.dev'})`, - }, { type: 'input', name: 'newEndpoint', message: `What's your scalars endpoint`, default: currentEndpoint, - when: ( answers ) => !answers.defaultEnvs - }, - { - type: 'input', - name: 'newClientId', - message: `What's your scalars client id`, - default: currentAuthorization, - when: ( answers ) => !answers.defaultEnvs + when: ( answers ) => ! answers.defaultEnvs }, { type: 'path', @@ -99,11 +89,10 @@ const loadEnvsAndIntrospect = ( interactive: boolean, endpoint: string | null, a } ] ).then( answers => { clientPath = answers.clientPath - if ( !answers.defaultEnvs && answers.newEndpoint && answers.newClientId ) { + if ( ! answers.defaultEnvs && answers.newEndpoint && answers.newClientId ) { currentEndpoint = answers.newEndpoint as string - currentAuthorization = answers.newClientId as string } - sync( currentEndpoint as string, currentAuthorization as string, clientPath, soft ) + sync( currentEndpoint as string, clientPath, soft ) } ) } @@ -112,12 +101,13 @@ const loadEnvsAndIntrospect = ( interactive: boolean, endpoint: string | null, a yargs( process.argv.slice( 2 ) ) .usage( `Usage: $0 ` ) .command( 'sync', 'Synchronize your client', ( { argv } ) => { - const prod: boolean = !!argv.p - const interactive: boolean = !!argv.i + const prod: boolean = !! argv.p + const interactive: boolean = !! argv.i const endpoint: string | null = ( argv.e as string ) || null const authorization: string | null = ( argv.a as string ) || null - const soft: boolean = !!argv.s - loadEnvsAndIntrospect( interactive, endpoint, authorization, prod, soft ) + const soft: boolean = !! argv.s + const env: string | null = argv.env as string || null + loadEnvsAndIntrospect( interactive, endpoint, authorization, env, prod, soft ) } ) .demand( 1, 'You must provide a valid scalars command' ) .help( 'h' ) @@ -131,6 +121,11 @@ yargs( process.argv.slice( 2 ) ) .option( 'e', { type: 'string', description: 'Make introspection with provided endpoint' } ) .alias( 'e', 'endpoint' ) .nargs( 'e', 1 ) + + .option( 'env', { type: 'string', description: 'Load enviroment file' } ) + .alias( 'env', 'enviroment' ) + .nargs( 'env', 1 ) + .option( 'a', { type: 'string', description: 'Make introspection with provided auth token' } ) .alias( 'a', 'authorization' ) .nargs( 'a', 1 ) diff --git a/src/tests/cli/env.test b/src/tests/cli/env.test new file mode 100644 index 0000000..b26bb8b --- /dev/null +++ b/src/tests/cli/env.test @@ -0,0 +1 @@ +SCALARS_ENDPOINT=https://devapp.kaury.co/app \ No newline at end of file diff --git a/src/tests/cli/introspection.spec.test.ts b/src/tests/cli/introspection.spec.test.ts new file mode 100644 index 0000000..b1ac424 --- /dev/null +++ b/src/tests/cli/introspection.spec.test.ts @@ -0,0 +1,43 @@ +import { exec } from 'child_process' + +describe( 'Suite cli introspection', () => { + it( 'should introspect with env in runtime', async ( ) => { + const status = await new Promise( ( resolve => { + const sync = exec( `SCALARS_ENDPOINT=https://devapp.kaury.co/app yarn ts-node dist/sync.js sync` ) + sync.on('exit', ( existCode: number ) => { + if ( existCode !== 0 ) { + resolve( false ) + return + } + resolve( true ) + } ) + } ) ) + expect( status ).toBeTruthy() + } ) + it( 'should introspect with env file path', async ( ) => { + const status = await new Promise( ( resolve => { + const sync = exec( `yarn ts-node dist/sync.js sync --env src/tests/cli/env.test` ) + sync.on('exit', ( existCode: number ) => { + if ( existCode !== 0 ) { + resolve( false ) + return + } + resolve( true ) + } ) + } ) ) + expect( status ).toBeTruthy() + } ) + it( 'should introspect with args command', async () => { + const status = await new Promise( ( resolve => { + const sync = exec( `yarn ts-node dist/sync.js sync --endpoint https://devapp.kaury.co/app` ) + sync.on('exit', ( existCode: number ) => { + if ( existCode !== 0 ) { + resolve( false ) + return + } + resolve( true ) + } ) + } ) ) + expect( status ).toBeTruthy() + } ) +} ) \ No newline at end of file diff --git a/src/__test__/client.seeds.ts b/src/tests/queries/client.seeds.ts similarity index 100% rename from src/__test__/client.seeds.ts rename to src/tests/queries/client.seeds.ts diff --git a/src/tests/queries/client.test.ts b/src/tests/queries/client.test.ts new file mode 100644 index 0000000..35e84d9 --- /dev/null +++ b/src/tests/queries/client.test.ts @@ -0,0 +1,340 @@ +import { exec } from 'child_process' + +describe( 'Suite fix this test', () => { + it.todo( 'should fix queries') +} ) + + +// // @ts-ignore +// import { Profile, ProfileSelect, ScalarsClient, ScalarsClientConfig } from '../../dist/index' +// import { faqSeeds, registrationSeeds } from './client.seeds' +// +// const client: ScalarsClient = new ScalarsClient( { endpoint: '', authorization: ''} as ScalarsClientConfig ) +// +// const idRegex: RegExp = new RegExp( `[0-9a-fA-F]{16}` ) +// const dateRegex: RegExp = new RegExp( `[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T(2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]\\.[0-9]{3}Z` ) +// const emailRegex: RegExp = new RegExp( `[a-zA-Z]+@[a-zA-Z]+.+` ) +// const { objectContaining, stringContaining, stringMatching, arrayContaining } = expect +// const { floor, random } = Math +// +// describe( `Registration`, () => { +// const { createRegistration, updateRegistration } = registrationSeeds +// describe( `Should read multiple and single registrations`, () => { +// let registrationId: string = '' +// test( `Should read registrations`, ( done ) => { +// client.query +// .registrations( { +// select: { id: true } +// } ) +// .then( ( res: Array ) => { +// expect( res ).toEqual( arrayContaining( [objectContaining( { +// id: stringMatching( idRegex ), +// } )] ) ) +// registrationId = res[floor( random() * res.length )].id || '' +// done() +// } ) +// .catch( ( err: unknown ) => { +// console.log( err ) +// } ) +// } ) +// test( `Should read registration`, ( done ) => { +// expect( registrationId ).toEqual( stringMatching( idRegex ) ) +// client.query +// .registration( { +// select: { email: true, name: true, createdAt: true, updatedAt: true, linkedin: true }, +// where: { id: registrationId } +// } ) +// .then( ( res: any ) => { +// expect( res ).toEqual( objectContaining( { +// email: stringMatching( emailRegex ), +// name: stringContaining( '' ), +// createdAt: stringMatching( dateRegex ), +// updatedAt: stringMatching( dateRegex ), +// linkedin: stringContaining( '' ) +// } ) ) +// done() +// } ) +// .catch( ( err: unknown ) => console.log( err ) ) +// } ) +// } ) +// describe( `Should create, update and delete registration`, () => { +// let registrationId: string = '' +// test( `Should create registration`, ( done ) => { +// client.mutation +// .createRegistration( { +// select: { id: true }, +// data: { +// email: createRegistration.email, +// name: createRegistration.name, +// linkedin: createRegistration.linkedin +// } +// } ) +// .then( ( res: any ) => { +// expect( res ).toEqual( objectContaining( { +// id: stringMatching( idRegex ) +// } ) ) +// registrationId = res.id || '' +// done() +// } ) +// .catch( ( err: unknown ) => console.log( err ) ) +// } ) +// test( `Should update registration`, ( done ) => { +// expect( registrationId ).toEqual( stringMatching( idRegex ) ) +// client.mutation +// .updateRegistration( { +// select: { id: true, name: true, email: true, linkedin: true, createdAt: true, updatedAt: true }, +// where: { id: registrationId }, +// data: { email: updateRegistration.email, name: updateRegistration.name } +// } ) +// .then( ( res: any ) => { +// expect( res ).toEqual( objectContaining( { +// id: stringContaining( registrationId ), +// name: stringContaining( updateRegistration.name ), +// email: stringContaining( updateRegistration.email ), +// linkedin: stringContaining( createRegistration.linkedin ), +// createdAt: stringMatching( dateRegex ), +// updatedAt: stringMatching( dateRegex ) +// } ) ) +// done() +// } ) +// .catch( ( err:unknown ) => console.log( err ) ) +// } ) +// test( `Should delete registration`, ( done ) => { +// expect( registrationId ).toEqual( stringMatching( idRegex ) ) +// client.mutation +// .deleteRegistration( { +// select: { id: true, name: true, email: true, createdAt: true, linkedin: true, updatedAt: true }, +// where: { id: registrationId } +// } ) +// .then( ( res: any ) => { +// expect( res ).toEqual( objectContaining( { +// id: stringContaining( registrationId ), +// name: stringContaining( updateRegistration.name ), +// email: stringContaining( updateRegistration.email ), +// createdAt: stringMatching( dateRegex ), +// linkedin: stringContaining( createRegistration.linkedin ), +// updatedAt: stringMatching( dateRegex ) +// } ) ) +// done() +// } ) +// .catch( ( err:unknown ) => console.log( err ) ) +// } ) +// } ) +// } ) +// +// describe( `Faq`, () => { +// const { createFaq, updateFaq } = faqSeeds +// describe( `Should read multiple and single faqs`, () => { +// let faqId: string = '' +// test( `Should read faqs`, ( done ) => { +// client.query +// .faqs( { +// select: { id: true } +// } ) +// .then( ( res: Array ) => { +// expect( res ).toEqual( arrayContaining( [objectContaining( { +// id: stringMatching( idRegex ) +// } )] ) ) +// faqId = res[floor( random() * res.length )].id || '' +// done() +// } ) +// .catch( ( err: unknown ) => { +// console.log( err ) +// } ) +// } ) +// test( `Should read faq`, ( done ) => { +// expect( faqId ).toEqual( stringMatching( idRegex ) ) +// client.query +// .faq( { +// select: { answer: true, question: true, createdAt: true, updatedAt: true }, +// where: { id: faqId } +// } ) +// .then( ( res: any ) => { +// expect( res ).toEqual( objectContaining( { +// answer: stringContaining( '' ), +// question: stringContaining( '' ), +// createdAt: stringMatching( dateRegex ), +// updatedAt: stringMatching( dateRegex ) +// } ) ) +// done() +// } ) +// .catch( ( err: unknown ) => console.log( err ) ) +// } ) +// } ) +// describe( `Should create, update and delete faq`, () => { +// let faqId: string = '' +// test( `Should create faq`, ( done ) => { +// client.mutation +// .createFaq( { +// select: { +// id: true +// }, +// data: { +// question: createFaq.question, +// answer: createFaq.answer +// } +// } ) +// .then ( ( res: any ) => { +// expect( res ).toEqual( objectContaining( { +// id: stringMatching( idRegex ) +// } ) ) +// faqId = res.id || '' +// done() +// } ) +// .catch( ( err:unknown ) => console.log( err ) ) +// } ) +// test( `Should update faq`, ( done ) => { +// expect( faqId ).toEqual( stringMatching( idRegex ) ) +// client.mutation +// .updateFaq( { +// select: { id: true, question: true, answer: true, createdAt: true, updatedAt: true }, +// where: { id: faqId }, +// data: { question: updateFaq.question } +// } ) +// .then( ( res: any ) => { +// expect( res ).toEqual( objectContaining( { +// id: stringContaining( faqId ), +// question: stringContaining( updateFaq.question ), +// answer: stringContaining( createFaq.answer ), +// createdAt: stringMatching( dateRegex ), +// updatedAt: stringMatching( dateRegex ) +// } ) ) +// done() +// } ) +// .catch( ( err: unknown ) => console.log( err ) ) +// } ) +// test( `Should delete faq`, ( done ) => { +// expect( faqId ).toEqual( stringMatching( idRegex ) ) +// client.mutation +// .deleteFaq( { +// select: { id: true, answer: true, question: true, createdAt: true, updatedAt: true }, +// where: { id: faqId } +// } ) +// .then( ( res: any ) => { +// expect( res ).toEqual( objectContaining( { +// id: stringContaining( faqId ), +// question: stringContaining( updateFaq.question ), +// answer: stringContaining( createFaq.answer ), +// createdAt: stringMatching( dateRegex ), +// updatedAt: stringMatching( dateRegex ) +// } ) ) +// done() +// } ) +// .catch( ( err:unknown ) => console.log( err ) ) +// } ) +// } ) +// } ) +// +// describe( `Profile`, () => { +// test( `Should read profile`, ( done ) => { +// const profileSelect: ProfileSelect = { +// id: true, email: true, description: true, phone: true, +// sentConnections: { +// id: true, createdAt: true, updatedAt: true, status: true, +// sender: { +// id: true, email: true, interests: true, +// user: { +// name: true, id: true, createdAt: true +// } +// }, +// receiver: { +// id: true, email: true, interests: true, +// user: { +// name: true, id: true, createdAt: true, +// } +// } +// }, +// founder_projects: { +// name: true, +// founders: { +// email: true +// }, +// requests: { +// id: true, status: true, createdAt: true, +// invitee: { +// email: true +// }, +// inviter: { +// email: true +// }, +// project: { +// name: true +// } +// } +// }, +// receivedConnections: { +// id: true, createdAt: true, updatedAt: true, status: true, +// sender: { +// id: true, email: true, interests: true, +// user: { +// name: true, id: true, createdAt: true +// } +// }, +// receiver: { +// id: true, email: true, interests: true, +// user: { +// name: true, id: true, createdAt: true +// } +// } +// }, +// user: { username: true } +// } +// client.query +// .profiles( { +// select: profileSelect, +// where: { user: { username: '+573145463091' } } +// } ) +// .then ( ( res: Array ) => { +// console.log( res ) +// done() +// } ) +// .catch( ( err: unknown ) => { +// console.log( err ) +// } ) +// } ) +// test.todo( `Should create profile`) +// test.todo( `Should update profile`) +// test.todo( `Should delete profile`) +// } ) +// +// describe( `Chat`, () => { +// test.todo( `Should read chat`) +// test.todo( `Should create chat`) +// test.todo( `Should update chat`) +// test.todo( `Should delete chat`) +// } ) +// +// describe( `Message`, () => { +// test.todo( `Should read message`) +// test.todo( `Should create message`) +// test.todo( `Should update message`) +// test.todo( `Should delete message`) +// } ) +// +// describe( `Connection`, () => { +// test.todo( `Should read connection`) +// test.todo( `Should create connection`) +// test.todo( `Should update connection`) +// test.todo( `Should delete connection`) +// } ) +// +// describe( `Project`, () => { +// test.todo( `Should read project`) +// test.todo( `Should create project`) +// test.todo( `Should update project`) +// test.todo( `Should delete project`) +// } ) +// +// describe( `Request`, () => { +// test.todo( `Should read request`) +// test.todo( `Should create request`) +// test.todo( `Should update request`) +// test.todo( `Should delete request`) +// } ) +// +// describe( `Comment`, () => { +// test.todo( `Should read comment` ) +// test.todo( `Should create comment`) +// test.todo( `Should update comment`) +// test.todo( `Should delete comment`) +// } ) diff --git a/src/utils/ScalarsClient.mustache b/src/utils/ScalarsClient.mustache index 8c6628c..e23f819 100644 --- a/src/utils/ScalarsClient.mustache +++ b/src/utils/ScalarsClient.mustache @@ -3,21 +3,6 @@ import { ApolloClient, ApolloLink, FetchPolicy, NormalizedCacheObject, InMemoryC import { setContext } from '@apollo/client/link/context' import { gql } from 'graphql-tag' import fetch from 'node-fetch' -import { config } from 'dotenv' -import { join } from 'path' - -let currentEndpoint: string = 'wololo'; -const prod: boolean = process.env.NODE_ENV === 'production'; -const { error, parsed } = config( { path: join( process.cwd(), `${prod ? '.env.prod' : '.env.dev'}` ) } ); - -if ( !error && parsed && parsed.SCALARS_ENDPOINT ) { - // Environment variables loaded successfully - currentEndpoint = parsed.SCALARS_ENDPOINT as string; -} else { - console.info( `ScalarsClientError: Couldn't load endpoint` ); -} - -// Service interface ApolloOptions { fetchPolicy?: FetchPolicy @@ -48,7 +33,7 @@ export class Service { constructor ( config: ScalarsClientConfig ) { this.scalarsApiClientManager = new ScalarsClientManager( - `${currentEndpoint}/api/v1`, + config.endpoint, config.authorization ) } @@ -206,7 +191,7 @@ export class MutationsService extends Service { // ScalarsClientManager -export type TokenFunction = ()=> string +export type TokenFunction = ()=> string | string export type FetchFunction = ( uri: string, options: any )=> Promise type ApolloClients = { diff --git a/src/utils/ScalarsClientManager.mustache b/src/utils/ScalarsClientManager.mustache index a29fabd..7d86534 100644 --- a/src/utils/ScalarsClientManager.mustache +++ b/src/utils/ScalarsClientManager.mustache @@ -2,7 +2,7 @@ import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, NormalizedCacheObjec import { setContext } from '@apollo/client/link/context'; import { ClientType } from './Service'; -export type TokenFunction = ()=> string +export type TokenFunction = ()=> string | string export type FetchFunction = ( uri: string, options: any )=> Promise type ApolloClients = { diff --git a/src/utils/Service.mustache b/src/utils/Service.mustache index 3baa568..128de47 100644 --- a/src/utils/Service.mustache +++ b/src/utils/Service.mustache @@ -32,7 +32,7 @@ export class Service { constructor ( config: ScalarsClientConfig ) { this.scalarsApiClientManager = new ScalarsClientManager( - `${process.env.SCALARS_ENDPOINT}/api/v1`, + config.endpoint, config.authorization ) } diff --git a/src/utils/interfaces.ts b/src/utils/interfaces.ts index 4330c22..8774c4a 100644 --- a/src/utils/interfaces.ts +++ b/src/utils/interfaces.ts @@ -1,6 +1,5 @@ export interface ScalarsClientConfig { endpoint: string - clientId: string, clientPath: string soft: boolean } diff --git a/src/utils/introspect.ts b/src/utils/introspect.ts index 22ed9b7..a15217c 100644 --- a/src/utils/introspect.ts +++ b/src/utils/introspect.ts @@ -1,10 +1,11 @@ import { generate } from '@graphql-codegen/cli' -import { join, resolve } from 'path' -import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs' +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs' import { render } from 'mustache' -import { ScalarsClientConfig } from './interfaces' +import { join, resolve } from 'path' import tsc, { TsConfigCompilerOptions } from 'tsc-prog' +import { ScalarsClientConfig } from './interfaces' + const selectTypes: Array> = [] const returnTypes: Array> = [] @@ -26,7 +27,7 @@ const generateTypedSchema = async ( scalarsEndpoint: string ): Promise = generates: { [join( __dirname, 'newTypes.ts' )]: { schema: scalarsEndpoint.endsWith( '/' ) ? `${scalarsEndpoint}api/v1` : `${scalarsEndpoint}/api/v1`, - plugins: ['typescript', 'typescript-operations'], + plugins: [ 'typescript', 'typescript-operations' ], } } }, false ) @@ -39,51 +40,10 @@ const generateTypedSchema = async ( scalarsEndpoint: string ): Promise = * fields that can be queried/are attached to each one. * @param config Client configuration (endpoint and client id) */ +// eslint-disable-next-line max-lines-per-function const updateScalarsClient = async ( operations: Record, config: ScalarsClientConfig ): Promise => { const outputPath = config.clientPath - !existsSync( outputPath ) && !!mkdirSync( outputPath, { recursive: true } ) - // const canPerformSoftIntrospection: boolean = config.soft - // && existsSync( resolve( outputPath, 'index.ts' ) ) - // if ( !canPerformSoftIntrospection ) { - // // ------------------------------------------------------------------------- - // // const scalarsClientManagerTemplate: string = readFileSync( - // // join( __dirname, 'templates', 'ScalarsClientManager.mustache' ) - // // ).toString() - // // writeFileSync( - // // resolve( outputPath, 'ScalarsClientManager.ts' ), - // // render( scalarsClientManagerTemplate, {} ) - // // ) - // // ------------------------------------------------------------------------- - // const scalarsClientTemplate: string = readFileSync( - // join( __dirname, 'templates', 'ScalarsClient.mustache' ) - // ).toString() - // writeFileSync( - // resolve( outputPath, 'index.ts' ), - // render( scalarsClientTemplate, {} ) - // ) - // // ------------------------------------------------------------------------- - // // const serviceTemplate: string = readFileSync( - // // join( __dirname, 'templates', 'Service.mustache' ) - // // ).toString() - // // writeFileSync( - // // resolve( outputPath, 'Service.ts' ), - // // render( serviceTemplate, {} ) - // // ) - // // ------------------------------------------------------------------------- - // // writeFileSync( - // // resolve( outputPath, 'index.ts' ), - // // `export * from './Service';\nexport * from './ScalarsClientManager';\nexport * from './ScalarsClient';\nexport * from './DefaultServices'; - // // ` - // // ) - // // ------------------------------------------------------------------------- - // // writeFileSync( - // // resolve( __dirname, 'index.ts' ), - // // `export * from './generated'` - // // ) - // } else { - // console.log( `Doing soft introspection!` ) - // } - // ------------------------------------------------------------------------- + ! existsSync( outputPath ) && !! mkdirSync( outputPath, { recursive: true } ) const schemaTypes = await generateTypedSchema( config.endpoint ) const defaultServicesTemplate: string = readFileSync( join( __dirname, 'templates', 'ScalarsClient.mustache' ) @@ -98,12 +58,10 @@ const updateScalarsClient = async ( operations: Record, config: Sca config } ) ) - // ------------------------------------------------------------------------- - // ------------------------------------------------------------------------- if ( outputPath === __dirname ) { try { - compile( [resolve( __dirname, 'index.ts' )], { + compile( [ resolve( __dirname, 'index.ts' ) ], { declaration: true, emitDeclarationOnly: false, target: 'es2019', @@ -116,8 +74,8 @@ const updateScalarsClient = async ( operations: Record, config: Sca outDir: __dirname, } ) } - catch ( e ) { - console.log( e ) + catch ( error ) { + console.info( error ) } } } @@ -150,7 +108,7 @@ const getFieldType = ( fieldType: Record ): Record => * This function builds types for operations responses * @param entity Entity to which the related queries or mutations responses will be build */ -const generateOperationsResponseTypes = ( entity: Record ): Record => { +const generateOperationsResponseTypes = ( entity: Record ): Record => { const selectType: Record = { name: `${entity.name}Select`, fields: entity.fields.map( ( field: Record ) => { @@ -160,7 +118,7 @@ const generateOperationsResponseTypes = ( entity: Record ): Record< } } ) } - if ( !selectTypes.some( select => select.name === selectType.name ) ) + if ( ! selectTypes.some( select => select.name === selectType.name ) ) selectTypes.push( selectType ) return selectType } @@ -201,7 +159,7 @@ const getOperationReturnType = ( type: Record, required: boolean = */ const getOperationArgType = ( arg: Record, required: boolean = false ): Record => { const { type: { kind, name, ofType } } = arg - let result: Record = {} + let result: Record = {} if ( /NON_NULL/gm.test( kind ) ) { result = getOperationArgType( { name: arg.name, type: ofType }, true ) } @@ -250,7 +208,7 @@ const getMutations = ( entity: Record, mutations: Array ) => { if ( getEntityFromOperation( mutation.type ) === entity.name ) { const operationReturn: Record = getOperationReturnType( mutation.type ) - if ( !returnTypes.some( ret => ret.type === operationReturn.type ) ) + if ( ! returnTypes.some( ret => ret.type === operationReturn.type ) ) returnTypes.push( operationReturn ) entityMutations.push( { operation: mutation.name, @@ -259,11 +217,11 @@ const getMutations = ( entity: Record, mutations: Array ) => getOperationArgType( arg ) ) - .sort( ( a: Record, b: Record ) => { - if ( a.requiredType && !b.requiredType ) { - return -1 + .sort( ( a: Record, b: Record ) => { + if ( a.requiredType && ! b.requiredType ) { + return - 1 } - if ( b.requiredType && !a.requiredType ) { + if ( b.requiredType && ! a.requiredType ) { return 1 } return 0 @@ -284,11 +242,11 @@ const getMutations = ( entity: Record, mutations: Array, queries: Array> ): Array> => { const entityQueries: Array> = [] - const select: Record = generateOperationsResponseTypes( entity ) + const select: Record = generateOperationsResponseTypes( entity ) queries.forEach( ( query: Record ) => { if ( getEntityFromOperation( query.type ) === entity.name ) { const operationReturn: Record = getOperationReturnType( query.type ) - if ( !returnTypes.some( ret => ret.type === operationReturn.type ) ) + if ( ! returnTypes.some( ret => ret.type === operationReturn.type ) ) returnTypes.push( operationReturn ) entityQueries.push( { operation: query.name, @@ -297,11 +255,11 @@ const getQueries = ( entity: Record, queries: Array ) => getOperationArgType( arg ) ) - .sort( ( a: Record, b: Record ) => { - if ( a.requiredType && !b.requiredType ) { - return -1 + .sort( ( a: Record, b: Record ) => { + if ( a.requiredType && ! b.requiredType ) { + return - 1 } - if ( b.requiredType && !a.requiredType ) { + if ( b.requiredType && ! a.requiredType ) { return 1 } return 0 @@ -327,18 +285,18 @@ const getServicesByOperations = ( objects: Array> ): Record< const queryObject: Record | undefined = objects .filter( ( object: Record ) => /^Query$/gm.test( object.name ) && - !/^.+Connection$/gm.test( object.name ) + ! /^.+Connection$/gm.test( object.name ) ).shift() const mutationObject: Record | undefined = objects .filter( ( object: Record ) => /^Mutation$/gm.test( object.name ) && - !/^.+Connection$/gm.test( object.name ) + ! /^.+Connection$/gm.test( object.name ) ).shift() const entitiesObjects: Array> = objects .filter( ( object: Record ) => - !/^Mutation$/gm.test( object.name ) && - !/^Query$/gm.test( object.name ) && - !/^.+Connection$/gm.test( object.name ) + ! /^Mutation$/gm.test( object.name ) && + ! /^Query$/gm.test( object.name ) && + ! /^.+Connection$/gm.test( object.name ) ) entitiesObjects.forEach( ( entity: Record ) => { operations.queries.push( ...getQueries( entity, queryObject?.fields ) ) @@ -357,7 +315,7 @@ const getIntrospectionFilteredByObjects = async ( scalarsEndpoint: string ): Pro generates: { 'introspection.json': { schema: scalarsEndpoint.endsWith( '/' ) ? `${scalarsEndpoint}api/v1` : `${scalarsEndpoint}/api/v1`, - plugins: ['introspection'], + plugins: [ 'introspection' ], config: { minify: false, descriptions: true, @@ -368,7 +326,7 @@ const getIntrospectionFilteredByObjects = async ( scalarsEndpoint: string ): Pro }, false ) const { '__schema': { types } }: Record = JSON.parse( content ) return types - .filter( ( type: any ) => /^OBJECT$/gm.test( type.kind ) && !/^__.+/gm.test( type.name ) ) + .filter( ( type: any ) => /^OBJECT$/gm.test( type.kind ) && ! /^__.+/gm.test( type.name ) ) } /** diff --git a/src/utils/template.mustache b/src/utils/template.mustache index f613940..5b1a4b6 100644 --- a/src/utils/template.mustache +++ b/src/utils/template.mustache @@ -5,7 +5,7 @@ import fetch from 'node-fetch'; import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, NormalizedCacheObject, FetchPolicy, gql } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; -type TokenFunction = ()=> string +type TokenFunction = ()=> string | string export interface ScalarsClientConfig { endpoint: string, diff --git a/tsconfig.json b/tsconfig.json index 3375185..a63cb05 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -10,32 +10,9 @@ "outDir": "./dist", "declaration": true, "declarationDir": "./dist/dts", - "emitDeclarationOnly": true, - "rootDir": "src", + "emitDeclarationOnly": true }, "include": ["./src/**/*.ts"], - "exclude": [".dist/**/*.ts", "./src/__test__/**/*"] -// "exclude": [".dist/**/*.ts"] + "exclude": [ ".dist/**/*.ts", "./src/__test__/**/*", "./src/tests/**/*" ] } -//{ -// "compilerOptions": { -// "allowJs": false, -// "allowSyntheticDefaultImports": true, -// "declaration": true, -// "declarationDir": "prebuild/types", -// "esModuleInterop": true, -// "outDir": "prebuild", -// "lib": ["es6", "dom", "es2016", "es2017"], -// "module": "CommonJS", -// "moduleResolution": "Node", -// "noEmit": false, -// "resolveJsonModule": true, -// "rootDir": "src", -// "sourceMap": false, -// "strict": true, -// "target": "ES5", -// "types": ["node"], -// }, -// "include": ["src/**/*"], -// "exclude": ["**/node_modules", "**/build", "**/dist", "**/*.md", "**/rollup.config.js"] -//} + From 9086fe10c94baa3cc376a120ce5ba2424db09a3d Mon Sep 17 00:00:00 2001 From: Carlos Guadir Date: Wed, 8 Sep 2021 12:34:39 -0500 Subject: [PATCH 6/8] Add no-cache config apollo --- src/utils/ScalarsClient.mustache | 2 +- src/utils/Service.mustache | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/ScalarsClient.mustache b/src/utils/ScalarsClient.mustache index e23f819..71fba0c 100644 --- a/src/utils/ScalarsClient.mustache +++ b/src/utils/ScalarsClient.mustache @@ -46,7 +46,7 @@ export class Service { const client: ApolloClient = this.scalarsApiClientManager.getClient( clientOptions?.client ) try { const response = await client.query( { - fetchPolicy: 'network-only', + fetchPolicy: 'no-cache', query, variables, ...clientOptions?.apolloOptions diff --git a/src/utils/Service.mustache b/src/utils/Service.mustache index 128de47..2d6f02d 100644 --- a/src/utils/Service.mustache +++ b/src/utils/Service.mustache @@ -45,7 +45,7 @@ export class Service { const client: ApolloClient = this.scalarsApiClientManager.getClient( clientOptions?.client ) try { const response = await client.query( { - fetchPolicy: 'network-only', + fetchPolicy: 'no-cache', query, variables, ...clientOptions?.apolloOptions From e016dc3bd9aee88c37a5c404aa0f40517113a682 Mon Sep 17 00:00:00 2001 From: LuisDanilo Date: Wed, 8 Sep 2021 12:40:56 -0500 Subject: [PATCH 7/8] deleted unused templates --- src/utils/DefaultServices.mustache | 104 ---------------- src/utils/ScalarsClientManager.mustache | 71 ----------- src/utils/Service.mustache | 85 ------------- src/utils/template.mustache | 154 ------------------------ 4 files changed, 414 deletions(-) delete mode 100644 src/utils/DefaultServices.mustache delete mode 100644 src/utils/ScalarsClientManager.mustache delete mode 100644 src/utils/Service.mustache delete mode 100644 src/utils/template.mustache diff --git a/src/utils/DefaultServices.mustache b/src/utils/DefaultServices.mustache deleted file mode 100644 index a4adf32..0000000 --- a/src/utils/DefaultServices.mustache +++ /dev/null @@ -1,104 +0,0 @@ -import { gql } from 'graphql-tag'; -import { ClientOptions, MutationClientOptions, Service } from './ScalarsClient' -import { DocumentNode } from 'graphql'; - -{{#schemaTypes}} -{{{.}}} -{{/schemaTypes}} - -{{#selects}} -export type {{name}} = { - {{#fields}} - {{name}}?: {{type}} - {{/fields}} -} -{{/selects}} - -const parseSelectFields = ( select: Record ): string => { - let fields: string = '' - Object.keys( select ).forEach( key => { - if ( typeof select[key] === 'boolean' ) { - fields = fields.concat( `${key} ` ) - } - else { - fields = fields.concat( `${key} { ${parseSelectFields( select[key] )}} ` ) - } - } ) - return fields -} - -const fillSelectedFields = ( operation: string, select: Record ): DocumentNode => { - return gql`${operation.replace( '#@@', parseSelectFields( select ) )}` -} - -export class QueriesService extends Service { - {{#operations}} - {{#queries}} - async {{operation}} ( args: { - select?: {{#select}}{{name}}{{/select}}, - {{#args}} - {{name}}{{^requiredType}}?{{/requiredType}}: {{{type}}}, - {{/args}} - clientOptions?: ClientOptions - } ): Promise<{{#return}}{{#list}}Array<{{{type}}}{{^requiredType}} | null{{/requiredType}}>{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}> { - const get{{_operation}}Query: string = ` - query get{{_operation}} ( - {{#args}} - ${{name}}: {{#scalarType}}{{.}}{{/scalarType}}{{^scalarType}}{{{type}}}{{/scalarType}}{{#requiredType}}!{{/requiredType}}, - {{/args}} - ) { - {{operation}} ( - {{#args}} - {{name}}: ${{name}}, - {{/args}} - ) { - #@@ - } - } - ` - const { {{operation}} } = await this.doQuery{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}>, Query{{_operation}}Args>( - fillSelectedFields( get{{_operation}}Query, args.select || { id: true } ), - Object.fromEntries( Object.entries( args ).filter( ( [ k, v ] ) => v !== null && k !== 'select' && k !== 'clientOptions' ) ) as Query{{_operation}}Args, - { ...args.clientOptions } - ) - return {{operation}} - } - {{/queries}} - {{/operations}} -} - -export class MutationsService extends Service { - {{#operations}} - {{#mutations}} - async {{operation}} ( args: { - select?: {{#select}}{{name}}{{/select}}, - {{#args}} - {{name}}{{^requiredType}}?{{/requiredType}}: {{{type}}}, - {{/args}} - clientOptions?: MutationClientOptions - } ): Promise<{{#return}}{{#list}}Array<{{{type}}}{{^requiredType}} | null{{/requiredType}}>{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}> { - const {{_operation}}Mutation: string = ` - mutation {{_operation}} ( - {{#args}} - ${{name}}: {{#scalarType}}{{.}}{{/scalarType}}{{^scalarType}}{{{type}}}{{/scalarType}}{{#requiredType}}!{{/requiredType}}, - {{/args}} - ) { - {{operation}} ( - {{#args}} - {{name}}: ${{name}}, - {{/args}} - ) { - #@@ - } - } - ` - const { {{operation}} } = await this.doMutation{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}>, Mutation{{_operation}}Args>( - fillSelectedFields( {{_operation}}Mutation, args.select || { id: true } ), - Object.fromEntries( Object.entries( args ).filter( ( [ k, v ] ) => v !== null && k !== 'select' && k !== 'clientOptions' ) ) as Mutation{{_operation}}Args, - { ...args.clientOptions } - ) - return {{operation}} - } - {{/mutations}} - {{/operations}} -} diff --git a/src/utils/ScalarsClientManager.mustache b/src/utils/ScalarsClientManager.mustache deleted file mode 100644 index 7d86534..0000000 --- a/src/utils/ScalarsClientManager.mustache +++ /dev/null @@ -1,71 +0,0 @@ -import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, NormalizedCacheObject, FetchPolicy, gql } from '@apollo/client'; -import { setContext } from '@apollo/client/link/context'; -import { ClientType } from './Service'; - -export type TokenFunction = ()=> string | string -export type FetchFunction = ( uri: string, options: any )=> Promise - -type ApolloClients = { - [key in ClientType]: { - client: ApolloClient|null - fetch?: FetchFunction - credentials?: string - token?: string - } -} - -export class ScalarsClientManager { - private readonly apolloClients: ApolloClients - private readonly defaultClientType: ClientType - private readonly cache: InMemoryCache - private readonly uri: string - - constructor ( uri: string, getToken: TokenFunction, defaultClientType: ClientType = ClientType.COOKIE ) { - if ( !uri ) { - throw new Error( 'URI is empty' ) - } - this.defaultClientType = defaultClientType; - this.uri = uri; - this.cache = new InMemoryCache( { addTypename: false } ) - this.apolloClients = { - [ClientType.CLIENT]: { - client: null, - credentials: 'omit', - token: getToken() - }, - [ClientType.COOKIE]: { - client: null, - credentials: 'include' - } - } - } - - getClient ( name: ClientType = this.defaultClientType, ssrMode: boolean = false ): ApolloClient { - const apolloClient = this.apolloClients[name] - if ( apolloClient && !apolloClient.client) { - const { credentials, token } = apolloClient - let authLink: ApolloLink | undefined; - if ( token ) { - authLink = setContext( ( _, { headers } ) => { - return { - headers: { ...headers, Authorization: token } - } - } ) - } - const httpLink = new HttpLink( { - uri: this.uri, - credentials, - fetch: fetch as any, - fetchOptions: { - credentials - } - } ) - apolloClient.client = new ApolloClient( { - link: authLink ? authLink.concat( httpLink ) : httpLink, - cache: this.cache, - ssrMode - } ) - } - return apolloClient.client as ApolloClient - } -} diff --git a/src/utils/Service.mustache b/src/utils/Service.mustache deleted file mode 100644 index 2d6f02d..0000000 --- a/src/utils/Service.mustache +++ /dev/null @@ -1,85 +0,0 @@ -import { ScalarsClientManager } from './ScalarsClientManager' -import { ScalarsClientConfig } from './ScalarsClient' -import { DocumentNode } from 'graphql' -import { ApolloClient, FetchPolicy, NormalizedCacheObject } from '@apollo/client' - -interface ApolloOptions { - fetchPolicy?: FetchPolicy -} - -export enum ClientType { - CLIENT = 'explicit', // THIS WILL REPLACE IMPLICIT - COOKIE = 'cookie', // THIS WILL REPLACE CODE -} - -export interface ClientOptions { - client?: ClientType - apolloOptions?: ApolloOptions -} - -interface MutationApolloOptions { - fetchPolicy?: Extract -} - -export interface MutationClientOptions { - client?: ClientType - auth?: boolean - apolloOptions?: MutationApolloOptions -} - -export class Service { - private readonly scalarsApiClientManager: ScalarsClientManager - - constructor ( config: ScalarsClientConfig ) { - this.scalarsApiClientManager = new ScalarsClientManager( - config.endpoint, - config.authorization - ) - } - - async doQuery ( - query: DocumentNode, - variables?: U, - clientOptions?: ClientOptions - ): Promise { - const client: ApolloClient = this.scalarsApiClientManager.getClient( clientOptions?.client ) - try { - const response = await client.query( { - fetchPolicy: 'no-cache', - query, - variables, - ...clientOptions?.apolloOptions - } ) - return Service.getResponse( response as any ) - } - catch ( error ) { - return Service.getResponse( { error } as any ); - } - } - - async doMutation ( - mutation: DocumentNode, - variables?: U, - clientOptions?: MutationClientOptions - ): Promise { - const client: ApolloClient = this.scalarsApiClientManager.getClient( clientOptions?.client ) - try { - const response = await client.mutate( { - mutation, - variables, - ...clientOptions?.apolloOptions - } ) - return Service.getResponse( response as any ) - } - catch ( error ) { - return Service.getResponse( { error } as any ); - } - } - - private static getResponse ( { data, error }: { data: T, error: T } ): T { - if ( data ) { - return data; - } - throw error; - } -} diff --git a/src/utils/template.mustache b/src/utils/template.mustache deleted file mode 100644 index 5b1a4b6..0000000 --- a/src/utils/template.mustache +++ /dev/null @@ -1,154 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ - -import { DocumentNode } from 'graphql' -import fetch from 'node-fetch'; -import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, NormalizedCacheObject, FetchPolicy, gql } from '@apollo/client'; -import { setContext } from '@apollo/client/link/context'; - -type TokenFunction = ()=> string | string - -export interface ScalarsClientConfig { - endpoint: string, - getToken: TokenFunction -} - -export enum ClientType { - CLIENT_ID = 'explicit', // THIS WILL REPLACE IMPLICIT - COOKIE = 'cookie', // THIS WILL REPLACE CODE -} - -type FetchFunction = ( uri: string, options: any )=> Promise -type ApolloClients = { - [key in ClientType]: { - client: ApolloClient|null - fetch?: FetchFunction - credentials?: string - token?: string - } -} - -interface ApolloOptions { - fetchPolicy?: FetchPolicy -} - -interface MutationApolloOptions { - fetchPolicy?: Extract -} - -interface ClientOptions { - client?: ClientType - auth?: boolean - apolloOptions?: ApolloOptions -} - -interface MutationClientOptions { - client?: ClientType - auth?: boolean - apolloOptions?: MutationApolloOptions -} - -{{#schemaTypes}} -{{{.}}} -{{/schemaTypes}} - -{{#selects}} -export type {{name}} = { - {{#fields}} - {{name}}?: {{type}} - {{/fields}} -} -{{/selects}} - -{{#returns}} -export type I{{type}} = Partial<{{{type}}}> -{{/returns}} - -const parseSelectFields = ( select: Record ): string => { - let fields: string = '' - Object.keys( select ).forEach( key => { - if ( typeof select[key] === 'boolean' ) { - fields = fields.concat( `${key} ` ) - } - else { - fields = fields.concat( `${key} { ${parseSelectFields( select[key] )}} ` ) - } - } ) - return fields -} - -const fillSelectedFields = ( operation: string, select: Record ): DocumentNode => { - return gql`${operation.replace( '#@@', parseSelectFields( select ) )}` -} - - -class QueriesService extends Service { - {{#operations}} - {{#queries}} - async {{operation}} ( args: { - select?: {{#select}}{{name}}{{/select}}, - {{#args}} - {{name}}{{^requiredType}}?{{/requiredType}}: {{{type}}}, - {{/args}} - clientOptions?: ClientOptions - } ): Promise<{{#return}}{{#list}}Array{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}I{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}> { - const get{{_operation}}Query: string = ` - query get{{_operation}} ( - {{#args}} - ${{name}}: {{#scalarType}}{{.}}{{/scalarType}}{{^scalarType}}{{{type}}}{{/scalarType}}{{#requiredType}}!{{/requiredType}}, - {{/args}} - ) { - {{operation}} ( - {{#args}} - {{name}}: ${{name}}, - {{/args}} - ) { - #@@ - } - } - ` - const { {{operation}} } = await this.doQuery{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}I{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}>, Query{{_operation}}Args>( - fillSelectedFields( get{{_operation}}Query, args.select || { id: true } ), - Object.fromEntries( Object.entries( args ).filter( ( [ k, v ] ) => v !== null && k !== 'select' && k !== 'clientOptions' ) ) as Query{{_operation}}Args, - { ...args.clientOptions, auth: {{#authOperation}}true{{/authOperation}}{{^authOperation}}false{{/authOperation}} } - ) - return {{operation}} - } - {{/queries}} - {{/operations}} -} - -class MutationsService extends Service { - {{#operations}} - {{#mutations}} - async {{operation}} ( args: { - select?: {{#select}}{{name}}{{/select}}, - {{#args}} - {{name}}{{^requiredType}}?{{/requiredType}}: {{{type}}}, - {{/args}} - clientOptions?: MutationClientOptions - } ): Promise<{{#return}}{{#list}}Array{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}I{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}> { - const {{_operation}}Mutation: string = ` - mutation {{_operation}} ( - {{#args}} - ${{name}}: {{#scalarType}}{{.}}{{/scalarType}}{{^scalarType}}{{{type}}}{{/scalarType}}{{#requiredType}}!{{/requiredType}}, - {{/args}} - ) { - {{operation}} ( - {{#args}} - {{name}}: ${{name}}, - {{/args}} - ) { - #@@ - } - } - ` - const { {{operation}} } = await this.doMutation{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}I{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}>, Mutation{{_operation}}Args>( - fillSelectedFields( {{_operation}}Mutation, args.select || { id: true } ), - Object.fromEntries( Object.entries( args ).filter( ( [ k, v ] ) => v !== null && k !== 'select' && k !== 'clientOptions' ) ) as Mutation{{_operation}}Args, - { ...args.clientOptions, auth: {{#authOperation}}true{{/authOperation}}{{^authOperation}}false{{/authOperation}} } - ) - return {{operation}} - } - {{/mutations}} - {{/operations}} -} From 80193fb0def180eeb63a045dfe2c26ceeeaddeef Mon Sep 17 00:00:00 2001 From: LuisDanilo Date: Wed, 8 Sep 2021 12:40:56 -0500 Subject: [PATCH 8/8] deleted unused templates --- src/__test__/client.test.ts | 0 src/utils/DefaultServices.mustache | 104 ---------------- src/utils/ScalarsClientManager.mustache | 71 ----------- src/utils/Service.mustache | 85 ------------- src/utils/template.mustache | 154 ------------------------ 5 files changed, 414 deletions(-) delete mode 100644 src/__test__/client.test.ts delete mode 100644 src/utils/DefaultServices.mustache delete mode 100644 src/utils/ScalarsClientManager.mustache delete mode 100644 src/utils/Service.mustache delete mode 100644 src/utils/template.mustache diff --git a/src/__test__/client.test.ts b/src/__test__/client.test.ts deleted file mode 100644 index e69de29..0000000 diff --git a/src/utils/DefaultServices.mustache b/src/utils/DefaultServices.mustache deleted file mode 100644 index a4adf32..0000000 --- a/src/utils/DefaultServices.mustache +++ /dev/null @@ -1,104 +0,0 @@ -import { gql } from 'graphql-tag'; -import { ClientOptions, MutationClientOptions, Service } from './ScalarsClient' -import { DocumentNode } from 'graphql'; - -{{#schemaTypes}} -{{{.}}} -{{/schemaTypes}} - -{{#selects}} -export type {{name}} = { - {{#fields}} - {{name}}?: {{type}} - {{/fields}} -} -{{/selects}} - -const parseSelectFields = ( select: Record ): string => { - let fields: string = '' - Object.keys( select ).forEach( key => { - if ( typeof select[key] === 'boolean' ) { - fields = fields.concat( `${key} ` ) - } - else { - fields = fields.concat( `${key} { ${parseSelectFields( select[key] )}} ` ) - } - } ) - return fields -} - -const fillSelectedFields = ( operation: string, select: Record ): DocumentNode => { - return gql`${operation.replace( '#@@', parseSelectFields( select ) )}` -} - -export class QueriesService extends Service { - {{#operations}} - {{#queries}} - async {{operation}} ( args: { - select?: {{#select}}{{name}}{{/select}}, - {{#args}} - {{name}}{{^requiredType}}?{{/requiredType}}: {{{type}}}, - {{/args}} - clientOptions?: ClientOptions - } ): Promise<{{#return}}{{#list}}Array<{{{type}}}{{^requiredType}} | null{{/requiredType}}>{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}> { - const get{{_operation}}Query: string = ` - query get{{_operation}} ( - {{#args}} - ${{name}}: {{#scalarType}}{{.}}{{/scalarType}}{{^scalarType}}{{{type}}}{{/scalarType}}{{#requiredType}}!{{/requiredType}}, - {{/args}} - ) { - {{operation}} ( - {{#args}} - {{name}}: ${{name}}, - {{/args}} - ) { - #@@ - } - } - ` - const { {{operation}} } = await this.doQuery{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}>, Query{{_operation}}Args>( - fillSelectedFields( get{{_operation}}Query, args.select || { id: true } ), - Object.fromEntries( Object.entries( args ).filter( ( [ k, v ] ) => v !== null && k !== 'select' && k !== 'clientOptions' ) ) as Query{{_operation}}Args, - { ...args.clientOptions } - ) - return {{operation}} - } - {{/queries}} - {{/operations}} -} - -export class MutationsService extends Service { - {{#operations}} - {{#mutations}} - async {{operation}} ( args: { - select?: {{#select}}{{name}}{{/select}}, - {{#args}} - {{name}}{{^requiredType}}?{{/requiredType}}: {{{type}}}, - {{/args}} - clientOptions?: MutationClientOptions - } ): Promise<{{#return}}{{#list}}Array<{{{type}}}{{^requiredType}} | null{{/requiredType}}>{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}> { - const {{_operation}}Mutation: string = ` - mutation {{_operation}} ( - {{#args}} - ${{name}}: {{#scalarType}}{{.}}{{/scalarType}}{{^scalarType}}{{{type}}}{{/scalarType}}{{#requiredType}}!{{/requiredType}}, - {{/args}} - ) { - {{operation}} ( - {{#args}} - {{name}}: ${{name}}, - {{/args}} - ) { - #@@ - } - } - ` - const { {{operation}} } = await this.doMutation{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}>, Mutation{{_operation}}Args>( - fillSelectedFields( {{_operation}}Mutation, args.select || { id: true } ), - Object.fromEntries( Object.entries( args ).filter( ( [ k, v ] ) => v !== null && k !== 'select' && k !== 'clientOptions' ) ) as Mutation{{_operation}}Args, - { ...args.clientOptions } - ) - return {{operation}} - } - {{/mutations}} - {{/operations}} -} diff --git a/src/utils/ScalarsClientManager.mustache b/src/utils/ScalarsClientManager.mustache deleted file mode 100644 index 7d86534..0000000 --- a/src/utils/ScalarsClientManager.mustache +++ /dev/null @@ -1,71 +0,0 @@ -import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, NormalizedCacheObject, FetchPolicy, gql } from '@apollo/client'; -import { setContext } from '@apollo/client/link/context'; -import { ClientType } from './Service'; - -export type TokenFunction = ()=> string | string -export type FetchFunction = ( uri: string, options: any )=> Promise - -type ApolloClients = { - [key in ClientType]: { - client: ApolloClient|null - fetch?: FetchFunction - credentials?: string - token?: string - } -} - -export class ScalarsClientManager { - private readonly apolloClients: ApolloClients - private readonly defaultClientType: ClientType - private readonly cache: InMemoryCache - private readonly uri: string - - constructor ( uri: string, getToken: TokenFunction, defaultClientType: ClientType = ClientType.COOKIE ) { - if ( !uri ) { - throw new Error( 'URI is empty' ) - } - this.defaultClientType = defaultClientType; - this.uri = uri; - this.cache = new InMemoryCache( { addTypename: false } ) - this.apolloClients = { - [ClientType.CLIENT]: { - client: null, - credentials: 'omit', - token: getToken() - }, - [ClientType.COOKIE]: { - client: null, - credentials: 'include' - } - } - } - - getClient ( name: ClientType = this.defaultClientType, ssrMode: boolean = false ): ApolloClient { - const apolloClient = this.apolloClients[name] - if ( apolloClient && !apolloClient.client) { - const { credentials, token } = apolloClient - let authLink: ApolloLink | undefined; - if ( token ) { - authLink = setContext( ( _, { headers } ) => { - return { - headers: { ...headers, Authorization: token } - } - } ) - } - const httpLink = new HttpLink( { - uri: this.uri, - credentials, - fetch: fetch as any, - fetchOptions: { - credentials - } - } ) - apolloClient.client = new ApolloClient( { - link: authLink ? authLink.concat( httpLink ) : httpLink, - cache: this.cache, - ssrMode - } ) - } - return apolloClient.client as ApolloClient - } -} diff --git a/src/utils/Service.mustache b/src/utils/Service.mustache deleted file mode 100644 index 2d6f02d..0000000 --- a/src/utils/Service.mustache +++ /dev/null @@ -1,85 +0,0 @@ -import { ScalarsClientManager } from './ScalarsClientManager' -import { ScalarsClientConfig } from './ScalarsClient' -import { DocumentNode } from 'graphql' -import { ApolloClient, FetchPolicy, NormalizedCacheObject } from '@apollo/client' - -interface ApolloOptions { - fetchPolicy?: FetchPolicy -} - -export enum ClientType { - CLIENT = 'explicit', // THIS WILL REPLACE IMPLICIT - COOKIE = 'cookie', // THIS WILL REPLACE CODE -} - -export interface ClientOptions { - client?: ClientType - apolloOptions?: ApolloOptions -} - -interface MutationApolloOptions { - fetchPolicy?: Extract -} - -export interface MutationClientOptions { - client?: ClientType - auth?: boolean - apolloOptions?: MutationApolloOptions -} - -export class Service { - private readonly scalarsApiClientManager: ScalarsClientManager - - constructor ( config: ScalarsClientConfig ) { - this.scalarsApiClientManager = new ScalarsClientManager( - config.endpoint, - config.authorization - ) - } - - async doQuery ( - query: DocumentNode, - variables?: U, - clientOptions?: ClientOptions - ): Promise { - const client: ApolloClient = this.scalarsApiClientManager.getClient( clientOptions?.client ) - try { - const response = await client.query( { - fetchPolicy: 'no-cache', - query, - variables, - ...clientOptions?.apolloOptions - } ) - return Service.getResponse( response as any ) - } - catch ( error ) { - return Service.getResponse( { error } as any ); - } - } - - async doMutation ( - mutation: DocumentNode, - variables?: U, - clientOptions?: MutationClientOptions - ): Promise { - const client: ApolloClient = this.scalarsApiClientManager.getClient( clientOptions?.client ) - try { - const response = await client.mutate( { - mutation, - variables, - ...clientOptions?.apolloOptions - } ) - return Service.getResponse( response as any ) - } - catch ( error ) { - return Service.getResponse( { error } as any ); - } - } - - private static getResponse ( { data, error }: { data: T, error: T } ): T { - if ( data ) { - return data; - } - throw error; - } -} diff --git a/src/utils/template.mustache b/src/utils/template.mustache deleted file mode 100644 index 5b1a4b6..0000000 --- a/src/utils/template.mustache +++ /dev/null @@ -1,154 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ - -import { DocumentNode } from 'graphql' -import fetch from 'node-fetch'; -import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, NormalizedCacheObject, FetchPolicy, gql } from '@apollo/client'; -import { setContext } from '@apollo/client/link/context'; - -type TokenFunction = ()=> string | string - -export interface ScalarsClientConfig { - endpoint: string, - getToken: TokenFunction -} - -export enum ClientType { - CLIENT_ID = 'explicit', // THIS WILL REPLACE IMPLICIT - COOKIE = 'cookie', // THIS WILL REPLACE CODE -} - -type FetchFunction = ( uri: string, options: any )=> Promise -type ApolloClients = { - [key in ClientType]: { - client: ApolloClient|null - fetch?: FetchFunction - credentials?: string - token?: string - } -} - -interface ApolloOptions { - fetchPolicy?: FetchPolicy -} - -interface MutationApolloOptions { - fetchPolicy?: Extract -} - -interface ClientOptions { - client?: ClientType - auth?: boolean - apolloOptions?: ApolloOptions -} - -interface MutationClientOptions { - client?: ClientType - auth?: boolean - apolloOptions?: MutationApolloOptions -} - -{{#schemaTypes}} -{{{.}}} -{{/schemaTypes}} - -{{#selects}} -export type {{name}} = { - {{#fields}} - {{name}}?: {{type}} - {{/fields}} -} -{{/selects}} - -{{#returns}} -export type I{{type}} = Partial<{{{type}}}> -{{/returns}} - -const parseSelectFields = ( select: Record ): string => { - let fields: string = '' - Object.keys( select ).forEach( key => { - if ( typeof select[key] === 'boolean' ) { - fields = fields.concat( `${key} ` ) - } - else { - fields = fields.concat( `${key} { ${parseSelectFields( select[key] )}} ` ) - } - } ) - return fields -} - -const fillSelectedFields = ( operation: string, select: Record ): DocumentNode => { - return gql`${operation.replace( '#@@', parseSelectFields( select ) )}` -} - - -class QueriesService extends Service { - {{#operations}} - {{#queries}} - async {{operation}} ( args: { - select?: {{#select}}{{name}}{{/select}}, - {{#args}} - {{name}}{{^requiredType}}?{{/requiredType}}: {{{type}}}, - {{/args}} - clientOptions?: ClientOptions - } ): Promise<{{#return}}{{#list}}Array{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}I{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}> { - const get{{_operation}}Query: string = ` - query get{{_operation}} ( - {{#args}} - ${{name}}: {{#scalarType}}{{.}}{{/scalarType}}{{^scalarType}}{{{type}}}{{/scalarType}}{{#requiredType}}!{{/requiredType}}, - {{/args}} - ) { - {{operation}} ( - {{#args}} - {{name}}: ${{name}}, - {{/args}} - ) { - #@@ - } - } - ` - const { {{operation}} } = await this.doQuery{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}I{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}>, Query{{_operation}}Args>( - fillSelectedFields( get{{_operation}}Query, args.select || { id: true } ), - Object.fromEntries( Object.entries( args ).filter( ( [ k, v ] ) => v !== null && k !== 'select' && k !== 'clientOptions' ) ) as Query{{_operation}}Args, - { ...args.clientOptions, auth: {{#authOperation}}true{{/authOperation}}{{^authOperation}}false{{/authOperation}} } - ) - return {{operation}} - } - {{/queries}} - {{/operations}} -} - -class MutationsService extends Service { - {{#operations}} - {{#mutations}} - async {{operation}} ( args: { - select?: {{#select}}{{name}}{{/select}}, - {{#args}} - {{name}}{{^requiredType}}?{{/requiredType}}: {{{type}}}, - {{/args}} - clientOptions?: MutationClientOptions - } ): Promise<{{#return}}{{#list}}Array{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}I{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}> { - const {{_operation}}Mutation: string = ` - mutation {{_operation}} ( - {{#args}} - ${{name}}: {{#scalarType}}{{.}}{{/scalarType}}{{^scalarType}}{{{type}}}{{/scalarType}}{{#requiredType}}!{{/requiredType}}, - {{/args}} - ) { - {{operation}} ( - {{#args}} - {{name}}: ${{name}}, - {{/args}} - ) { - #@@ - } - } - ` - const { {{operation}} } = await this.doMutation{{^requiredList}} | null {{/requiredList}}{{/list}}{{^list}}I{{{type}}}{{^requiredType}} | null{{/requiredType}}{{/list}}{{/return}}>, Mutation{{_operation}}Args>( - fillSelectedFields( {{_operation}}Mutation, args.select || { id: true } ), - Object.fromEntries( Object.entries( args ).filter( ( [ k, v ] ) => v !== null && k !== 'select' && k !== 'clientOptions' ) ) as Mutation{{_operation}}Args, - { ...args.clientOptions, auth: {{#authOperation}}true{{/authOperation}}{{^authOperation}}false{{/authOperation}} } - ) - return {{operation}} - } - {{/mutations}} - {{/operations}} -}