yargs argv not working anymore after update to latest version - yargs

I had this code
const argv = yargs
.option("applyChanges", {
alias: "a",
description: "Apply the changes",
type: "boolean"
})
.help()
.alias("help", "h").argv;
const options = {
applyChanges: argv.applyChanges ? argv.applyChanges : false
};
to get argv.applyChanges boolean value. But after the latest update to yargs 17 I get an error on argv.applyChanges saying
property 'applyChanges' does not exist on type '{ [x: string]: unknown; applyChanges: boolean | undefined; _: (string | number)[]; $0: string; } | Promise<{ [x: string]: unknown; applyChanges: boolean | undefined; _: (string | number)[]; $0: string; }>'.
Property 'applyChanges' does not exist on type 'Promise<{ [x: string]: unknown; applyChanges: boolean | undefined; _: (string | number)[]; $0: string; }>'.
I tried to use await but without success.
What should I do?
This code was working with the previous yargs version 16.x.x

The type of argv is a union. The first item is the arguments and the second one is a promise which resolves to those arguments.
The reason it's a union is because in yargs you can have commands, and the handlers for those commands can be asynchronous. And so .argv would resolve after that command finishes.
In the example, you aren't using any asynchronous commands, but yargs typing doesn't know that when you are just calling .argv or .parse.
What you need to do is use parseSync which explicitally tells yargs you have no asynchronous commands (this will also throw errors if there are async commands).
const argv = yargs
.option("applyChanges", {
alias: "a",
description: "Apply the changes",
type: "boolean"
})
.help()
.alias("help", "h").parseSync();
const options = {
applyChanges: argv.applyChanges ? argv.applyChanges : false
};

Related

Apollo client ignoring argument for GQL REST query

I have a query that is defined like this:
export const getProjectCosts = gql`
query GetProjectCosts($projectId: Int) {
ProjectCostList #rest(type: "ProjectCostList", path: "ProjectCosts/{args.projectId}") {
id
projectId
cost
description
costType
budgetYear
createdByUser
createdDate
}
}
`;
export const useGetProjectCostsListQuery = (baseOptions?: QueryHookOptions<ProjectCostList>) => {
const options = { ...baseOptions };
return useQuery<ProjectCostList>(getProjectCosts, options);
};
I call it like this:
const {
loading: projectCostLoading,
error: projectCostError,
data: projectCostData,
} = useGetProjectCostsListQuery({
variables: {
projectId: args.defaultValues.id,
},
});
I have verified in the debugger that the argument is sent correctly.
However, in the browser I see a warning:
Warning: RestLink caught an error while unpacking ProjectCosts/{args.projectId}|args.projectId This tends to happen if you forgot to pass a parameter needed for creating an #rest(path, or if RestLink was configured to deeply unpack a path parameter that wasn't provided. This message will only log once per detected instance. Trouble-shooting hint: check #rest(path: and the variables provided to this query.
(anonymous) # restLink.ts:567
And a request is sent to api/ProjectCosts/ instead of api/ProjectCosts/1234, which not surprisingly fails with a HTTP 404 error.
Is this a bug or am I doing something wrong?
I found this issue on Github, which looks very similar to what I'm experiencing.
We're using a custom .NET backend.
If it's a bug, is there a workaround?
The problem was that the parameter has to be declared twice.
This is the solution:
export const getProjectCosts = gql`
query GetProjectCosts($projectId: Int!) {
ProjectCostList(projectId: $projectId) #rest(type: "ProjectCostList", path: "ProjectCosts/{args.projectId}") {

How can I troubleshoot an error: lib/graphql has no exported mutation - for a mutation I have defined and which appears in graphql.tsx

I'm trying to figure out what I need to do in order to have lib/graphql recognise the mutations I have made.
I have an issue.tsx (which is a form). It imports:
import {
IssueInput,
useUpdateIssueMutation,
useAllIssuesQuery,
useCreateIssueMutation,
useDeleteIssueMutation,
Issue as IssueGQLType,
} from "lib/graphql"
Other than IssueInput and Issue, I'm getting errors in my terminal that say these queries and mutations are not exported members.
However when I try to load the issue page in local host, I get an error that says:
error - GraphQLError [Object]: Syntax Error: Expected Name, found
. It points to the line where Issue is imported.
I made all of these queries and mutations in my resolver as follows:
import { Arg, Mutation, Query, Resolver } from "type-graphql"
import { Issue } from "./issue.model"
import { IssueService } from "./issue.service"
import { IssueInput } from "./inputs/create.input"
import { Inject, Service } from "typedi"
import { UseAuth } from "../shared/middleware/UseAuth"
import { Role } from "#generated"
#Service()
#Resolver(() => Issue)
export default class IssueResolver {
#Inject(() => IssueService)
issueService: IssueService
#Query(() => [Issue])
async allIssues() {
return await this.issueService.getAllIssues()
}
#Query(() => [Issue])
async futureRiskIssues() {
return await this.issueService.getFutureRiskIssues()
}
#Query(() => Issue)
async issue(#Arg("id") id: string) {
return await this.issueService.getIssue(id)
}
#UseAuth([Role.ADMIN])
#Mutation(() => Issue)
async createIssue(#Arg("data") data: IssueInput) {
return await this.issueService.createIssue(data)
}
#UseAuth([Role.ADMIN])
#Mutation(() => Issue)
async deleteIssue(#Arg("id") id: string) {
return await this.issueService.deleteIssue(id)
}
#UseAuth([Role.ADMIN])
#Mutation(() => Issue)
async updateIssue(#Arg("id") id: string, #Arg("data") data: IssueInput) {
return await this.issueService.updateIssue(id, data)
}
}
I can also see from my graphql.tsx file, that these functions are recognised as follows:
export type Mutation = {
__typename?: 'Mutation';
createIssue: Issue;
createUser: User;
deleteIssue: Issue;
destroyAccount: Scalars['Boolean'];
forgotPassword: Scalars['Boolean'];
getBulkSignedS3UrlForPut?: Maybe<Array<SignedResponse>>;
getSignedS3UrlForPut?: Maybe<SignedResponse>;
login: AuthResponse;
register: AuthResponse;
resetPassword: Scalars['Boolean'];
updateIssue: Issue;
updateMe: User;
};
export type MutationCreateUserArgs = {
data: UserCreateInput;
};
export type MutationDeleteIssueArgs = {
id: Scalars['String'];
};
export type MutationUpdateIssueArgs = {
data: IssueInput;
id: Scalars['String'];
};
I have run the codegen several times and can't think of anything else to try to force these mutations and queries to be recognised. Can anyone see a way to trouble shoot this?
My codegen.yml has:
schema: http://localhost:5555/graphql
documents:
- "src/components/**/*.{ts,tsx}"
- "src/lib/**/*.{ts,tsx}"
- "src/pages/**/*.{ts,tsx}"
overwrite: true
generates:
src/lib/graphql.tsx:
config:
withMutationFn: false
addDocBlocks: false
scalars:
DateTime: string
plugins:
- add:
content: "/* eslint-disable */"
- typescript
- typescript-operations
- typescript-react-apollo
When I look at the mutations available on the authentication objects (that are provided with the [boilerplate app][1] that I am trying to use), I can see that there are mutations and queries that are differently represented in the lib/graphql file. I just can't figure out how to force the ones I write to be included in this way:
export function useLoginMutation(baseOptions?: Apollo.MutationHookOptions<LoginMutation, LoginMutationVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useMutation<LoginMutation, LoginMutationVariables>(LoginDocument, options);
}
Instead, I get all of these things, but none of them look like the above and I can't figure out which one to import into my front end form so that I can make an entry in the database. None of them look like the queries or mutations I defined in my resolver
export type IssueInput = {
description: Scalars['String'];
issueGroup: Scalars['String'];
title: Scalars['String'];
};
export type IssueListRelationFilter = {
every?: InputMaybe<IssueWhereInput>;
none?: InputMaybe<IssueWhereInput>;
some?: InputMaybe<IssueWhereInput>;
};
export type IssueRelationFilter = {
is?: InputMaybe<IssueWhereInput>;
isNot?: InputMaybe<IssueWhereInput>;
};
export type IssueWhereInput = {
AND?: InputMaybe<Array<IssueWhereInput>>;
NOT?: InputMaybe<Array<IssueWhereInput>>;
OR?: InputMaybe<Array<IssueWhereInput>>;
createdAt?: InputMaybe<DateTimeFilter>;
description?: InputMaybe<StringFilter>;
id?: InputMaybe<UuidFilter>;
issueGroup?: InputMaybe<IssueGroupRelationFilter>;
issueGroupId?: InputMaybe<UuidFilter>;
subscribers?: InputMaybe<UserIssueListRelationFilter>;
title?: InputMaybe<StringFilter>;
updatedAt?: InputMaybe<DateTimeFilter>;
};
export type IssueWhereUniqueInput = {
id?: InputMaybe<Scalars['String']>;
};
I do have this record in my graphql.tsx file:
export type Mutation = {
__typename?: 'Mutation';
createIssue: Issue;
createIssueGroup: IssueGroup;
createUser: User;
deleteIssue: Issue;
deleteIssueGroup: IssueGroup;
destroyAccount: Scalars['Boolean'];
forgotPassword: Scalars['Boolean'];
getBulkSignedS3UrlForPut?: Maybe<Array<SignedResponse>>;
getSignedS3UrlForPut?: Maybe<SignedResponse>;
login: AuthResponse;
register: AuthResponse;
resetPassword: Scalars['Boolean'];
updateIssue: Issue;
updateIssueGroup: IssueGroup;
updateMe: User;
};
but I can't say: createIssueMutation as an import in my issue.tsx where I'm trying to make a form to use to post to the database.
[1]: https://github.com/NoQuarterTeam/boilerplate
In the issue form, I get an error that says:
"resource": "/.../src/pages/issue.tsx", "owner": "typescript",
"code": "2305", "severity": 8, "message": "Module '"lib/graphql"'
has no exported member 'useCreateIssueMutation'.", "source": "ts",
"startLineNumber": 7, "startColumn": 27, "endLineNumber": 7,
"endColumn": 54 }]
and the same thing for the query
check your codegen.yml
overwrite: true
schema: "http://localhost:4000/graphql"
documents: "src/graphql/**/*.graphql"
generates:
src/generated/graphql.tsx:
plugins:
- "typescript"
- "typescript-operations"
- "typescript-react-apollo"
./graphql.schema.json:
plugins:
- "introspection"
or try something like #Resolver(Issue)
It seems like you are not generating the hooks that you are trying to import.
You can update your codegen.yml file to add the generated hooks:
schema: http://localhost:5555/graphql
documents:
- "src/components/**/*.{ts,tsx}"
- "src/lib/**/*.{ts,tsx}"
- "src/pages/**/*.{ts,tsx}"
overwrite: true
generates:
src/lib/graphql.tsx:
config:
withMutationFn: false
addDocBlocks: false
scalars:
DateTime: string
withHooks: true # <--------------------- this line
plugins:
- add:
content: "/* eslint-disable */"
- typescript
- typescript-operations
- typescript-react-apollo

RPC-CORE: getApps(acc: AccountId): undefined:: -32602: Invalid params: 0x prefix is missing. Error: -32602: Invalid params: 0x prefix is missing

const api = await ApiPromise.create({provider:wsProvider,
rpc:{
cf:{
getApps:{
description:"JUST For Test",
params:[{
name:"acc",
type:"AccountId"
}]
}
}
}});
const alice = keyring.addFromUri('//Alice');
let ker = crypto.encodeDerivedAddress(alice.publicKey,0);
let d = await api.rpc.cf.getApps(ker);
Rust Pallet Code
//function which I am calling
pub fn get_apps(acc:T::AccountId)->Vec<Vec<u8>>{
let data = <AppStore<T>>::get(acc);
data
}
Rust RPC
use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
use jsonrpc_derive::rpc;
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_runtime::{generic::BlockId,traits::Block as BlockT};
use std::sync::Arc;
use cf_runtime::AppApi as AppStorageApi;
#[rpc]
pub trait AppApi<BlockHash,AccountId>{
#[rpc(name="cf_getApps")]
fn get_apps(&self,at:Option<BlockHash>,acc:AccountId)->Result<Vec<Vec<u8>>>;
}
I have tried other prefix like 42 , 5 ,2 but not getting success , I did't understand anything how this error come again and again , and what is the default prefix for substrate node.

Cypress: cy.window(): Unable to get property values

Goal
Hello, I wish to gather custom property values for a window object of a page using cy.window().
Issue
When using cy.log() jointly with JSON.stringify(), it presents that it does have properties with values; however, when using lodash _.has(), does not have these properties and thereby no value because these properties are not found.
Code
The following Cypress custom command using cy.window() gathers custom window's property
export function cmdCypressWindow($propName: string) {
cy.window()
.its($propName)
.then(($propValue: Cypress.AUTWindow) => {
cy.log('props names:', JSON.stringify(Object.getOwnPropertyNames($propValue), null, 2));
cy.log('props values:', JSON.stringify($propValue, null, 2));
cy.log('VERSION prop:', _.has($propValue, 'VERSION'));
cy.log('HOST prop:', _.has($propValue, 'HOST'));
cy.log('VERSION value:', _.get($propValue, 'VERSION'));
cy.log('HOST value:', _.get($propValue, 'HOST'));
});
}
Passed in for parameter $propName value 'ACT', because I am expecting the page's window object to contain window.ACT["VERSION"].
Using the example code, the log output shows that the page's window does contain property ACT["VERSION"].
However, when accessing this window object, listed properties are unavailable and undefined:
window
- its .ACT
log props names:, [ "__esModule", "VERSION", "HOST", "RulesList", "RulesAddEdit", "AppsList", "AppsOAuth", "AppsAdd" ]
log props values:, { "VERSION": "0.2.11", "HOST": "radmin" }
log VERSION prop:, false
log HOST prop:, false
log VERSION value:
log HOST value:
How do I resolve this? Thank you, all feedback is very much appreciated.
Found part of the solution here:
TypeScript: Find Key / Value in Object (list comprehension?)
Modified the function:
export function cmdCypressWindow($propName: string) {
cy.window()
.its($propName)
.then(($propValue: Cypress.AUTWindow) => {
const actValues: Record<string, string> = {};
Object.keys($propValue).forEach(key => {
// #ts-ignore
if (typeof $propValue[key] !== 'function') {
// #ts-ignore
actValues[key as string] = $propValue[key];
}
});
cy.log(`window.${$propName}`, JSON.stringify(actValues, null, 2));
cy.wrap(actValues);
});
}
Results show that I was able to acquire values from window object:
log props names:, [ "__esModule", "VERSION", "HOST", "RulesList", "RulesAddEdit", "AppsList", "AppsOAuth", "AppsAdd" ]
log window.ACT, { "VERSION": "0.2.11", "HOST": "radmin" }
wrap {version: 0.2.11, host: radmin}

Input Object type `TypeName` must define one or more fields

I am experimenting with NestJS and TypeGraphQL. And I have an example model of a cat.
import { Document } from 'mongoose';
import { ObjectType, InputType, Field, ID } from 'type-graphql';
export interface Cat extends Document {
readonly name: string;
readonly age?: number;
}
class CatBase {
#Field()
name: string;
#Field({ nullable: true })
age?: number;
}
#ObjectType()
export class CatObjectType extends CatBase implements Cat {
#Field(type => ID)
id: string;
}
#InputType()
export class CatInputType extends CatBase implements Cat {
}
Here I am trying to reuse BaseCat in CatObjectType and CatInputType. But I getting this error:
[ { GraphQLError: Input Object type CatInputType must define one or more fields.
at SchemaValidationContext.reportError (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:90:19)
at validateInputFields (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:432:13)
at validateTypes (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:240:7)
at validateSchema (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:54:3)
at graphqlImpl (/Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:79:62)
at /Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:28:59
at new Promise (<anonymous>)
at Object.graphql (/Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:26:10)
at Function.<anonymous> (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:18:52)
at Generator.next (<anonymous>)
at /Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:110:75
at new Promise (<anonymous>)
at Object.__awaiter (/Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:106:16)
at Function.generateFromMetadata (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:15:24)
at /Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/utils/buildSchema.js:11:65
at Generator.next (<anonymous>)
message:
'Input Object type CatInputType must define one or more fields.' } ]
(node:72485) UnhandledPromiseRejectionWarning: Error: Generating schema error
at Function.<anonymous> (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:20:27)
at Generator.next (<anonymous>)
at fulfilled (/Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:107:62)
at processTicksAndRejections (internal/process/next_tick.js:81:5)
(node:72485) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:72485) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
When in CatInputType are described all fields from BaseCat all work as expected. What I am doing wrong?
TypeGraphQL by default doesn't inherit all #Fields from parent classes that are not decorated with #InputType or #ObjectType because this types should not be mixed as things like unions and interfaces are invalid GraphQL input types.
So if you are sure you're not violating this rules, just place both decorators on top of the class:
#ObjectType({ isAbstract: true })
#InputType({ isAbstract: true })
class CatBase {
#Field()
name: string;
#Field({ nullable: true })
age?: number;
}

Resources