🦁

svelte-apollo (svelte + apollo client)、GraphQL操作の導入メモ

2021/06/30に公開

概要:

svelteで。GraphQL(apollo) の導入メモとなります


環境

  • svelte: 3.0.0
  • @apollo/client 3.3.20
  • svelte-apollo 0.4.0
  • node 14

関連

https://github.com/timhall/svelte-apollo

https://zenn.dev/masaino/articles/fc6edab52251f9


追加手順

  • 上記関連に沿った手順で進めますがエラーで起動できない状況になりましたので

修正方法等、下記になります。


  • svelte追加後、@apollo/client 追加
* npx degit sveltejs/template app123
* npm i --save @apollo/client graphql

  • svelte-apollo追加
* npm i --save svelte-apollo @rollup/plugin-graphql @rollup/plugin-replace

  • この後 上記のgitの、App.svelteに。ApolloClient追加すると。エラーになりましたので

下記、process関係がでました

policies.js:150 Uncaught ReferenceError: process is not defined
    at Policies.setRootTypename (policies.js:150)
    at new Policies (policies.js:47)
    at new InMemoryCache (inMemoryCache.js:42)

  • 修正方法、rollup.config.js 修正

https://gist.github.com/kuc-arc-f/48150aa214e7442494f76970f5b1ccbb

  • @rollup/plugin-replace追加

  • export default > plugins修正 > replace追加

rollup.config.js
import replace from '@rollup/plugin-replace';

export default {
  ...

  	plugins: [
		replace({
			'process.env.NODE_ENV': JSON.stringify( 'development' )
		})
    ...
    ]
}
  • 上記でエラー消えました

GraphQL動作テスト

  • query
App.js
import { ApolloClient, InMemoryCache ,gql} from "@apollo/client";
import { setClient ,query } from "svelte-apollo";

const client = new ApolloClient({
	uri: "http://localhost:4000/graphql",
	cache: new InMemoryCache(),
});
setClient(client);

const GET_TASKS = gql`
  query {
    tasks {
      id
      title
    }
  }
`;
const get_items = async function(){
  const data = await client.query({
    query: GET_TASKS, fetchPolicy: "network-only"
  })
  console.log(data)
}
get_items()
  • mutation : ハンドラ起動し、レコード追加
App.js

//
const get_gql_add= function(title){
  return gql`
    mutation {
      addTask( title: "${title}") {
        id
        title
      }                
    }      
  `   
}
async function handleClick() {
console.log('clicked')
  await add_item()
}
async function add_item(){
  try {
    const result = await client.mutate({mutation: get_gql_add("hoge")}) 
console.log(result)   
  } catch (error) {
    console.error(error);
  }    
}

参考のコード

https://github.com/kuc-arc-f/svelte2_4apollo

....

Discussion