Tips for importing queries from a .graphql file using Angular and TypeScript

I am currently developing an app using Angular and Ionic. For the backend, I have set up a node server running ApolloServer with Neo4j (utilizing grandstarter.io). On the frontend, I have a file named queries.ts where I define my graphql queries in the following format:

supplierByName = (value) => {
    const query = gql`
    {
        Supplier(filter: {name: "${value}"}) {
            name
        }
    }
    `;

    return query;
};

To execute my graphql query using apollo, I call it like this:

this.apollo.query({
                query: this.queries.supplierByName(supplierName)
            })
            .subscribe(....)

However, I find having my graphql queries as strings cumbersome and would prefer to store them directly in a .graphql file for better tooling and readability. Here is how I envision the contents of the queries.graphql file:

query supplierByName($value: String) {
 Supplier(filter: { name: "$value}" }) {
    name
 }
}

Then, when executing the graphql query with Apollo, I aim to do something like this:

 import supplierByName from './queries.graphql'
 .....
 this.apollo.query({
                query: supplierByName(supplierName)
            })
            .subscribe(....)

This approach seems more straightforward to me. I have come across some resources on Stack Overflow and dev.to that discuss similar concepts, but they seem to focus on ApolloServer rather than client-side implementation. I am working with Angular 8.1.2 and would appreciate any insights or resources related to this setup.

The examples in the Apollo documentation typically demonstrate building queries using strings and gql (graphql-tag). I am looking to streamline this process by utilizing .graphql files directly.

Answer №1

To begin, integrate a webpack loader into your webpack configuration as outlined in the Apollo documentation.

loaders: [
  {
    test: /\.(graphql|gql)$/,
    exclude: /node_modules/,
    loader: 'graphql-tag/loader'
  }
]

Remember not to use double quotation marks within your .graphql file for variables. Your queries.graphql file should look like this:

query supplierByName($value: String) {
 Supplier(filter: { name: $value }) {
    name
 }
}

Lastly, make sure to pass variables to your query in the following way:

import supplierByName from './queries.graphql'
 .....
 this.apollo.query({
  query: supplierByName,
  variables: {
    value: supplierName, // your value
  }
})
  .subscribe(....)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered during conversion to Typescript for select event and default value

When trying to set the defaultValue in a Select component, TSlint throws an error - Type 'string' is not assignable to type 'ChangeEvent<HTMLInputElement> | undefined - for the code snippet below: const App = () => { const [ mont ...

The TypeScript error "Issue with Type Assertion: 'This expression is not callable Type'...' has no call signatures" occurs when there is a missing semicolon

Here's a simplified version of our original code: const start: number = 10 const end: number = 20 (someElement as HTMLInputElement).setSelectionRange(start, end) We encountered an error with the 20, where a red squiggly line appeared indicating ...

Angular dynamically filling in a table with incomplete object data

I am currently working on a scientific project that involves displaying large amounts of data in tables. The experiments I'm working with have timestamps that follow this format: interface TimeData { time: string; data: {SD: string, SEM: string ...

I have a Visual Studio 2019 solution that consists of two projects - one is an Angular project and the other is written in TypeScript. I have successfully configured

We are currently utilizing Visual Studio 2019 (not the VS Code version) for our project. Within this solution, we have multiple projects included. One of these projects contains Angular code that we compile using the traditional 'ng build' comma ...

The onChange event does not work as expected for Select controls

I am facing an issue with my common useForm.tsx file when handling the onChange event for select controls. The error message I encounter is displayed below. Does anyone have any suggestions on how to resolve this? Error: Type '(e: ChangeEvent<HTM ...

What is the correct way to install @angular-devkit/build-angular in Angular version 13?

In my Angular 13 project, I am facing a dilemma with conflicting dev dependencies: "devDependencies": { "@angular-devkit/build-angular": "~13.2.5", "@angular/cli": "~13.2.5", "@angular/co ...

Arranging an array of objects in Javascript based on the first attribute, and in cases of equality, sorting with another attribute

I have an array structured like this: let myarr = [{id:1 , name: "mark" , birthday: "1990-08-18"}, {id:2 , name: "fred" , birthday: "1990-08-17"}, {id:3 , name: "franck" , birthday: "1990-08-16"}, ...

Tips for placing a marker at the center of the screen on Google Maps

I am developing a transportation app similar to Uber or Lyft using JavaScript. I am looking to retrieve the map location with the center of the screen, where there is a marker located at y = 0 and x = 0. Similar to the image below: The user should be abl ...

What is the best approach to upgrade this React Native code from version 0.59.10 to version 0.72.5?

I am encountering an issue with the initialRouteName: 'Notifications' property, while working on my React Native code. Despite trying various solutions, I have not been successful in resolving it. As a newcomer to React Native, any assistance wou ...

Ways to duplicate a column value in a reusable table

Hi there! Currently, I am implementing a smart table (i.e reusable table) in our application. I need to send data through settings from one component file and retrieve it in the reusable component. However, I am facing an issue with binding nested values i ...

Describing the implementation of UNO out parameters within definitions

The UNO API offers support for inout and out parameters. In this scenario, a variable is passed into a function, the function modifies the variable, and the updated value of the variable can be accessed outside the function. Javascript lacks native suppor ...

Upon refreshing the page, an error occurred stating: 'ReferenceError: unable to access the lexical declaration 'BaseRepository' before initialization'

In my code, I have an abstract class called BaseRepository which includes a client instance and some general functions. The AuthRepository class inherits from the BaseRepository. Additionally, there is an AuthService module that utilizes the AuthRepository ...

What causes TypeScript to display an 'Object is potentially undefined' error message when utilizing array.at(-1)?

An issue arises in Typescript with the error message "Object is possibly 'undefined'" when attempting to access an element at a negative index using array.at(-1).key //array[array.length - 1].key. This error does not occur in the following code: ...

Redirect to a new page following a toastr notification in an Angular application

Looking for a way to automatically navigate to another page after a toastr notification disappears. showToasterWarning(){ this.notifyService.showWarning("No Data Found for this Date!", ""); } The notifyService is responsible ...

Disabling specific time slots in the mat select functionality

I have a scenario where I need to display time slots at 30-minute intervals using Mat Select. export const TIME=["12:00 AM","12:30 AM","01:00 AM","01:30 AM","02:00 AM","02:30 AM","03:00 AM&qu ...

Error in Node: JSON parse failure due to invalid token "'<'" and ""<!DOCTYPE ""

Every time I attempt to run node commands or create a new Angular project, I encounter the following error. Node version 20.11.0 NPM version 10.2.4 https://i.sstatic.net/Dg6BU.png https://i.sstatic.net/ZwN1Q.png ...

The type 'Object' is missing the property 'properties' for this object

I am dealing with the following code snippet: spear.ts: export class Spears { constructor( id: string = null, transaction_id: string = null, spear_id: number = null, delivery_date: any = null, delivery_time: an ...

Angular's auto suggestion dropdown feature activates when the "@" symbol is typed, prompting users

I need to develop an autocomplete dropdown feature in my Angular 8 project. The idea is that when a user types "@" in the text box, it should display suggestions for usernames based on data from a web service or JSON file. I looked into using angular-me ...

The Angular ngFor function is unable to locate a suitable change supporting the object '[object Object]'

Struggling to iterate on an Observable of the RxJS store state using: ngOnInit() { this.route.params .subscribe( (params: Params) => { this.index = +params['propertyId']; this.propertyState = this.store.select('property ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...