在 React Native 中使用 apollo-upload-client 上传图片

Upload images with apollo-upload-client in React Native

我现在正在试用 Prisma 和 React Native。目前我正在尝试使用包 _apollo-upload-client (https://github.com/jaydenseric/apollo-upload-client) 将图像上传到我的数据库。但它并没有那么顺利。

目前我可以 select 一张来自 Expo 的 ImagePicker 图片。然后我尝试使用 Apollo Client 进行修改:

await this.props.mutate({
  variables: {
    name,
    description,
    price,
    image,
  },
});

但是我收到以下错误:

Network error: JSON Parse error: Unexpected identifier "POST"
- node_modules/apollo-client/bundle.umd.js:76:32 in ApolloError
- node_modules/apollo-client/bundle.umd.js:797:43 in error

而且我相信它来自这些代码行:

const image = new ReactNativeFile({
  uri: imageUrl,
  type: 'image/png',
  name: 'i-am-a-name',
});

这与他们的示例几乎相同,https://github.com/jaydenseric/apollo-upload-client#react-native

imageUrl 来自我的州。当我 console.log image 我得到以下信息:

ReactNativeFile {
  "name": "i-am-a-name",
  "type": "image/png",
  "uri": "file:///Users/martinnord/Library/Developer/CoreSimulator/Devices/4C297288-A876-4159-9CD7-41D75303D07F/data/Containers/Data/Application/8E899238-DE52-47BF-99E2-583717740E40/Library/Caches/ExponentExperienceData/%2540anonymous%252Fecommerce-app-e5eacce4-b22c-4ab9-9151-55cd82ba58bf/ImagePicker/771798A4-84F1-4130-AB37-9F382546AE47.png",
}

所以有东西突然冒出来了。但我不能再进一步了,我希望我能从某人那里得到一些提示。

我也没有包含任何来自后端的代码,因为我认为问题出在前端。 但是 如果有人想看一下后端,我可以更新问题,或者您可以在这里看一下:https://github.com/Martinnord/Ecommerce-server/tree/image_uploads.

非常感谢阅读!干杯。

更新

在有人询问服务器中的逻辑后,我决定在下面通过它:

Product.ts

// import shortid from 'shortid'
import { createWriteStream } from 'fs'

import { getUserId, Context } from '../../utils'

const storeUpload = async ({ stream, filename }): Promise<any> => {
    // const path = `images/${shortid.generate()}`
    const path = `images/test`

    return new Promise((resolve, reject) =>
      stream
        .pipe(createWriteStream(path))
        .on('finish', () => resolve({ path }))
        .on('error', reject),
    )
  }

const processUpload = async upload => {
    const { stream, filename, mimetype, encoding } = await upload
    const { path } = await storeUpload({ stream, filename })
    return path
}

export const product = {
  async createProduct(parent, { name, description, price, image }, ctx: Context, info) {
    // const userId = getUserId(ctx)
    const userId = 1;
    console.log(image);
    const imageUrl = await processUpload(image);
    console.log(imageUrl);
    return ctx.db.mutation.createProduct(
      {
        data: {
            name,
            description,
            price,
            imageUrl,
            seller: {
                connect: { id: userId },
            },
        },
      },
      info
    )
  },
}

通过你的代码爬取,我找到了 this 存储库,如果我没记错的话,那一定是 front-end 代码?

如您所述,apollo-upload-server 需要一些额外的 set-up,您项目的 front-end 部分也是如此。您可以找到更多相关信息 here.

据我所知,你的代码中有问题的部分一定是阿波罗客户端的初始化。根据我的观察,您已将 Apollo 所需的所有内容放入 src/index 文件夹中,但未包含 Apollo Upload Client 本身。

我从我的一个项目中创建了一个要点,它初始化了 Apollo Upload Client 以及其他一些东西,但我想你会发现自己不明白。

https://gist.github.com/maticzav/86892448682f40e0bc9fc4d4a3acd93a

希望对您有所帮助!

已找到解决方案。

我有点尴尬,这是我遇到的问题,我什至不知道我是否应该接受这个答案,因为我在解决这个问题时感到很尴尬。但是....

我的代码没有问题,但是依赖版本有问题。我试图回溯我应用程序上的所有内容,所以我决定从头开始并创建一个新帐户。我希望它能正常工作,但我收到了这个错误:

Error: Cannot use GraphQLNonNull "User!" from another module or realm.

Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.

https://yarnpkg.com/en/docs/selective-version-resolutions

Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.

然后我明白有些事情(我没有想到)是错误的。我检查了我的依赖项版本并将它们与 Graphcool 的示例 https://github.com/graphcool/graphql-server-example/blob/master/package.json 进行了比较。而且我注意到我的依赖项已经过时了。所以我升级了它们,一切正常!所以这就是我必须做的。更新我的依赖项。

故事的寓意

总是,总是检查你该死的依赖版本...