使用 TypeScript 来进行 GraphQL Hygraph。

huangapple go评论89阅读模式
英文:

Using typescript for graphql hygraph

问题

我正在使用React并且第一次与TypeScript一起使用目前正在使用Hygraph构建博客但在查询后我认为我定义变量的方式有问题我看到有人在使用@types/node但我仍然不明白如何使用它

```javascript
import { request, gql } from "graphql-request";

declare var process : {
  env: {
    GRAPHQL_API_ENDPOINT: string
  }
}

const graphqlAPI: string = process.env.GRAPHQL_API_ENDPOINT;

export const getPosts = async (): Promise<any> => {
  const query: string = gql`
    query Assets {
       //queries here
    }
  `;
  const result: any = await request(graphqlAPI, query);
  return result.postsConnection.edges;
};

这是环境变量:

process.env.GRAPHQL_API_ENDPOINT = //api

<details>
<summary>英文:</summary>

So i am using react and first time using it with typescript, currently building a blog using hygraph but after i query it i think something is wrong with how i defined my variables. I saw someone someone using @types/node but i still dont understand how to use it.

import { request, gql } from "graphql-request";

declare var process : {
env: {
GRAPHQL_API_ENDPOINT: string
}
}

const graphqlAPI: string = process.env.GRAPHQL_API_ENDPOINT;

export const getPosts = async (): Promise<any> => {
const query: string = gql
query Assets {
//queries here
}
;
const result: any = await request(graphqlAPI, query);
return result.postsConnection.edges;
};


and this is the env:

process.env.GRAPHQL_API_ENDPOINT = //api


</details>


# 答案1
**得分**: 1

在你的 `.env` 文件中,像这样添加变量 -

```lang-sh
GRAPHQL_API_ENDPOINT=//api

注意没有空格。修改你的文件看起来像这样 -

import { request, gql } from "graphql-request";

const graphqlAPI: string = process.env.GRAPHQL_API_ENDPOINT!;

export const getPosts = async (): Promise<any> => {
  const query: string = gql`
    query Assets {
       //queries here
    }
  `;
  const result: any = await request(graphqlAPI, query);
  return result.postsConnection.edges;
};

确保已安装 @types/node 并且在你的 tsconfig.json 的 lib 选项中,存在一个值 node。这应该可以解决问题。

英文:

In your .env file, add the variable like this -

GRAPHQL_API_ENDPOINT=//api

Notice there's no space. Modify your file to look like this -

import { request, gql } from &quot;graphql-request&quot;;

const graphqlAPI: string = process.env.GRAPHQL_API_ENDPOINT!;

export const getPosts = async (): Promise&lt;any&gt; =&gt; {
  const query: string = gql`
    query Assets {
       //queries here
    }
  `;
  const result: any = await request(graphqlAPI, query);
  return result.postsConnection.edges;
};

Make sure that @types/node is installed and in your tsconfig.json's lib option, there's a value node present in the array. That should take care of it.

huangapple
  • 本文由 发表于 2023年8月5日 07:36:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定