Get-Fields
get-fields was made with the intention of using the same graphql schema but with different fields. Where it is not necessary to create a new schema, but change the fields in the function call.
Install with npm
npm i get-fields
Usage
For example, if we want to create a schema to access user data, we can use this function in schema creation:
import getFields from "get-fields";
export function GET_USER() {
const fields = getFields(arguments); // Returns the selected fields
return gql`
query {
getUser {
${fields} // Adds the selected fields inside the *route*
}
}`;
}
When using the schema, you must pass the fields you want to return separated by commas.
const Profile = () => {
const { data } = useQuery(GET_USER("id", "name", "contact"));
// [...]
};
But if you have to access nested data, you must use nesting object as in the example below:
const Table = () => {
const { data } = useQuery(
GET_SCHEDULE(
"id",
// object usage
{ name: "createdBy", items: ["_id", "name", "contact"] },
{ name: "service", items: ["_id", "duration", "price"] },
"date",
"status"
)
);
// [...]
};
The nesting object are used to access the fields of the fields.
All objects must have two properties:
- name - Field name;
-
items - Array of fields that will be returned:
- fields - Strings or nesting object.
Example of using the nesting object:
{ name: "createdBy", items: ["_id", "name", "contact"]}
The example of using createdBy in graphql schema:
query {
schedules {
date
createdBy {
id
name
contact
}
}
}
Items can also receive nesting object
{ name: "date", items: ["id", { name: "location", items: ["street", "house"] }] }
The above example in graphql schema:
query {
schedules {
date {
id
location {
street
house
}
}
}
}