无场景,就是做做看,试试 API 随便写写,现在有几个问题想请教各位仁兄
Env
Code
Nitro
现在我通过
export default defineNitroPlugin((nitroApp) => {
const link = new HttpLink({
uri: 'http://localhost:8080/v1/graphql',
headers: {
'x-hasura-admin-secret': '123456'
}
});
const apolloClient = new ApolloClient({
cache: new InMemoryCache(),
link: link
});
nitroApp.hooks.hook('request', (event) => {
event.context.apollo = apolloClient
})
})
------------------------Handler---------------------------------
import { gql } from '@apollo/client/core'
export default defineEventHandler(async (event) => {
const client = event.context.apollo
const query = gql`
query getUser($limit: Int!) {
User(limit: $limit) {
id
name
}
User_aggregate {
aggregate {
count
}
}
}
`
const { limit } = await readBody(event)
try {
const { data } = await client.query({ query, variables: { limit: 10 } })
return data
} catch (error) {
console.error('GraphQL query error:', error)
return { error: 'Failed to fetch data' }
}
})
连接本地的 Hasura 服务,Hasura 是动态管理 GraphQL 的 Schema 的一个服务,这个服务我链接了 PGSQL ,具体的环境如下
version: '3.6'
services:
postgres:
image: postgres:16.3
restart: always
environment:
POSTGRES_USER: root
POSTGRES_PASSWORD: root
POSTGRES_DB: rm00
ports:
- "5432:5432"
volumes:
- ./postgres:/var/lib/postgresql/data
hasura:
restart: always
image: hasura/graphql-engine:v2.15.2
ports:
- "8080:8080"
depends_on:
- postgres
environment:
HASURA_GRAPHQL_DATABASE_URL: postgres://root:root@postgres:5432/rm00
HASURA_GRAPHQL_ENABLE_CONSOLE: "true"
HASURA_GRAPHQL_ENABLE_ALLOWLIST: "true"
HASURA_GRAPHQL_ADMIN_SECRET: 123456
Nuxt 的前台
Login
{{ data }}
{{ error }}
整个 demo 跑通了是跑通了,但是总觉得不是一个很好的方式或者说不成熟,现在有几个问题想请教请教大佬们
Question