uniapp+graphql

谭昕
2023-12-01

我再网上查了很久,几乎都没有可以用的
1、安装依赖
npm install graphql graphql-tag
2、在应用市场导入luch-request
3、进行graphql封装,新建graphql.js文件

import Request from '@/utils/luch-request/luch-request/index.js'
const httpGraphql = new Request()

//请求拦截器
httpGraphql.interceptors.request.use((config) => { // 可使用async await 做异步操作
	//const token = uni.getStorageSync('token');
	// if (token) {
	config.header = {
		Authorization: "xxxxxxx"
	}
	//}

	// if (config.method === 'POST') {
	//     config.data = JSON.stringify(config.data);
	// }
	return config
}, error => {
	return Promise.resolve(error)
})

// 响应拦截器
httpGraphql.interceptors.response.use((response) => {
	console.log(response)
	return response
}, (error) => {
	//未登录时清空缓存跳转
	// if (error.statusCode == 401) {
	//     uni.clearStorageSync();
	//     uni.switchTab({
	//         url: "/pages/index/index.vue"
	//     })
	// }
	return Promise.resolve(error)
})


export default httpGraphql

4、api.js调用接口

import httpGraphql from "@/utils/graphql.js"
import gql from 'graphql-tag'
import {
	print
} from 'graphql'
import {
	graphqlUrl
} from "@/config/netConfig.js"


export function test() {
	let postData = gql`
	      query {
	        users {
	          id
	          account
	          name
	          sex
	          department
	          phone
	          role
	          canPost
	          createTime
	          createBy {
	            name
	          }
	          projects {
	            id
	          }
	        }
	      }`
	return httpGraphql.post(graphqlUrl, {
		query: print(postData)
	})
}


5、降低"@babel/runtime": “~7.12.0”
6、在根目录下新建vue.config.js文件

module.exports = {
    chainWebpack: (config) => {
        // GraphQL Loader
        config.module // optional
            .rule('graphql')
            .test(/\.graphql$/)
            .use('graphql-tag/loader')
            .loader('graphql-tag/loader')
            .end()

        config.module
            .rule('mjs')
            .test(/\.mjs$/)
            .include.add(/node_modules/)
            .end()
            .type('javascript/auto')
            .end()

        config.resolve.extensions
            .add('.mjs')
            .add('.gql')
            .add('.graphql')
            .end()
    }
}

至此大工告成!!!
参考: https://lichengwu.net/uni-app-graphql/

 类似资料: