I am working with graphql.
My backend is finaly set and now im working on sending queries from my frontend to my backend.
Imagine this query:
{
login(Email:"MyEmail", Password:"MyCoolPasswordHello")
{token
refreshToken}
}
I was thinking that I could try to make my queries reuasable in the frontend so I created a queries file and did this:
export enum QueryNames {
login = 'login',
}
export const getQuery = (query: QueryNames, params: any): any => {
const queries = {
login: `{login(${params}){token refreshToken}}`,
}[query];
if (!queries) return {};
return queries;
};
export const query = (queryName: QueryNames, params: any) => getQuery(queryName, params);
It gets called like this:
console.log(getQuery(QueryNames.login, { Email: "Hello", Password: "HelloPassword" }));
Result:
{login([object Object]){token refreshToken}}
I could change my login to
export const getQuery = (query: QueryNames, params: any): any => {
const queries = {
login: `{login(Emai:${params.Email} Password: ${params.Password}){token refreshToken}}`,
}[query];
if (!queries) return {};
return queries;
};
And then I get the desired result.
Is there a way of doing it so that my property names and values get read instead of me explicitly having to set Email:
and Password:
?
took me a while but solved it like this:
export const makeArray = (obj) => Array.from(Object.keys(obj), k => [`${k}`, obj[k]]);
and using it like this:
export const getQuery = (query: QueryNames, params: any): any => {
const props = makeArray(params);
// @ts-ignore
// eslint-disable-next-line array-callback-return
const funcParams = props.map(current => `${current[0]} : ${current[1]} `);
const queries = {
login: `mutation {login(${funcParams}){token refreshToken}}`,
}[query];
if (!queries) return {};
return queries;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.