Taro,GraphQL,NestJS

Taro, Graphql, NestJS, MongoDB 开发姿势。

Taro封装Apollo请求库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// /api/graphql.ts

import Taro from '@tarojs/taro'
import ApolloClient from 'apollo-boost'

const uri = 'https://xxx.com/graphql'

const fetch = (url, { body: data, ...fetchOptions }) => {
return Taro.request({ url, data, ...fetchOptions, dataType: 'txt', responseType: 'text' })
.then((res) => {
res.text = () => Promise.resolve(res.data)
return res
}).catch(error => {
console.error(error)
},
);
}

export default new ApolloClient({ uri, fetch })
1
2
3
4
5
6
7
8
9
10
11
12
13
// /api/gql.ts

import { gql } from 'apollo-boost'

export const category = gql`
query {
category {
name
id
image
}
}
`
1
2
3
4
5
// page.ts

import { category } from '~/api/gql'

const res = await graphql.query({ query: category })

Taro图片url转base64

某业务需要通过相机拍照,以base64的形式上传到服务端。然而Taro.createCameraContext返回的是图片在本地缓存地址,而不是图片文件,无法转换为base64,Taro中也没相应的文档。后来发现,原来Taro是小程序的子集,在Taro中也能使用wx的API.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// func.ts

export function url2base64(url) {
return new Promise((resolve, reject) => {
wx.getFileSystemManager().readFile({
filePath: url,
encoding: 'base64',
success: res => {
resolve(res.data)
},
fail: (err) => {
reject(err)
}
})
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// page.ts

import {url2base64} from '~/func.js'

onCamera = () => {
const ctx = Taro.createCameraContext()
ctx.takePhoto({
quality: 'high',
success: async res => {
const base64 = await url2base64(res.tempImagePath)
const { width, height } = await Taro.getImageInfo({ src: res.tempImagePath })
this.handleCanvas(base64, res.tempImagePath, { width, height })
}
})
}

NestJS方面略麻烦,有时间补充……

查看评论