Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8922

GraphQLでファイルアップロード

$
0
0

GraphQLでファイルアップロード

GraphQL(Appolo Server)でファイルをアップロードする。
サーバ側はnode.jsを使う。
クライアントはAltair GraphQL Clientと使う。

サンプルのソースコードは以下。

事前準備

Get started with Apollo Server - Apollo Server - Apollo GraphQL Docsに従う。

$ mkdir graphql-server-example ;\
  cd graphql-server-example
$ npm init --yes
$ npm install apollo-server graphql

サーバ

File uploads - Apollo Server - Apollo GraphQL Docsをほぼそのまま使う。
若干の変更として、アップロードが成功したときにメッセージを表示するように変更。

file-uploads/index.js
const{ApolloServer,gql}=require('apollo-server');consttypeDefs=gql`
  type File {
    filename: String!
    mimetype: String!
    encoding: String!
  }

  type Query {
    uploads: [File]
  }

  type Mutation {
    singleUpload(file: Upload!): File!
  }
`;constresolvers={Query:{uploads:(parent,args)=>{},},Mutation:{singleUpload:(parent,args)=>{returnargs.file.then(file=>{console.log(`📁 File get ${file.filename}`);returnfile;});},},};constserver=newApolloServer({typeDefs,resolvers,});server.listen().then(({url})=>{console.log(`🚀 Server ready at ${url}`);});

サーバを起動する。

$ node file-uploads/index.js
🚀 Server ready at http://localhost:4000/

クライアント

アップロードするファイルの準備。

echo "FOO" > file-uploads/foo.txt

Altair GraphQL Clientでファイルをアップロードする。

altair.gif

それぞれ以下を入力しSend Requestを実行。

  • URL
http://localhost:4000
  • graphQL query
mutation($file: Upload!){
  singleUpload(file: $file){
    filename
    mimetype
    encoding
  }
}
  • Choose file
foo.txt
  • File name
file

成功すればサーバに以下のログが出力される。

📁 File get foo.txt

Viewing all articles
Browse latest Browse all 8922

Trending Articles