Cem Kaan
Cem Kaan

Reputation: 2236

How to integrate Apollo with NativeScript vue?

How to consume GraphQL API from a Nativescript-vue application?

How to modify it for nativescript-vue?

Should vue-apollo package work directly? There are even some examples of "apollo with angular". But unfortunately I couldn't find instruction for nativescript-vue. @khalifa-gad said it works fine with nativescript core. But does it work also with nativescript-vue?

There is an complete implementation with angular.

Angular answer is:

import { NativeScriptModule } from 'nativescript-angular/nativescript.module';
import { NativeScriptHttpClientModule } from 'nativescript-angular/http-client';
import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';

@NgModule({
  imports: [
    NativeScriptModule,
    NativeScriptHttpClientModule, // this provides HttpClient
    ApolloModule,
    HttpLinkModule
  ]
})
export class AppModule {
  constructor(
    apollo: Apollo,
    httpLink: HttpLink
  ) {
    // create Apollo
    apollo.create({
      link: httpLink.create({ uri }),
      // other options like cache
    });
  }
}

Upvotes: 1

Views: 718

Answers (3)

Colibri
Colibri

Reputation: 733

I used cem kaan's answer to make it work - so thank you for that.

However, in my case it needed some adjustments. To make it easier for everyone, I'll describe what exactly I did (excluding all my fixed mistakes, of course :D ) which takes a while. Points 1, 5, 6, 7 and 10 mainly base on cem's own answer. The other ones are either new or heavily adjusted due to changes in the way apollo is included.

Side note: I use typescript, so if you use javascript, you might have to adapt it a little more and use .js files instead of .ts files.


Setting up NativeScript-vue with GraphQL / Apollo

  1. Open the terminal in your project and install apollo-boost by entering one of these two commands

    - yarn add vue-apollo apollo-boost graphql
    
    - npm i vue-apollo apollo-boost graphql
    
  2. (Optional for quick testing) Create a new file called in your project root called ".graphqlconfig"

  3. (Optional for quick testing) Open the file and paste this + adapt it according to your personal endpoints

          {
            "name": "Your Schema",
            "schemaPath": "https://your.url.com/graphql",
            "extensions": {
              "endpoints": {
                "Default GraphQL Endpoint": {
                  "url": "https://your.url.com/graphql",
                  "headers": {
                    "user-agent": "TS GraphQL"
                  },
                  "introspect": false
                }
              }
            }
          }
  1. I use vscode and have installed the plugins ApolloGraphQL and GraphQL to simplify working with graphql.

  2. Create a new folder called "graphql"

  3. Create a new file in there called "queries.ts"

  4. Add your queries. The file could look like this:

        import { gql } from "apollo-boost";
        export const GET_ITEMS = gql`
        query GetItemsQuery {
            getItems {
              id, name, image
            }
        }
        `;
  1. If you installed the plugins as stated in 4, you'll be able to directly try and execute the queries inside the queries.ts file.

  2. Now open your main.ts and add the following lines

        // [...] imagine here your other imports like nativescript-vue or devtools
    
        import ApolloClient from "apollo-boost"
        import VueApollo from "vue-apollo"

        const apolloProvider = new VueApollo({
          defaultClient: new ApolloClient({
            uri: "https://your.url.com/graphql"
          })
        })

        Vue.use(VueApollo)

        // [...] your other stuff like DevTool use or configuration

        new Vue({
          provide: apolloProvider.provide(),
          render: h => h('frame', [h(App)])
        }).$start()
  1. In your *.vue file (my path: project/app/components) include the query for example like this list, first in the template section:
        <template>
    
           // [...] if this is not an imported component, here could be <Page> etc
    
           <GridLayout columns="*" rows="*,30">
              <Label v-if="$apollo.loading" text="loading ...  " textWrap="true" row="0" col="0" />
              <GridLayout v-else rows="*" columns="*" row="0" col="0">
                <ListView for="item in getItems" row="0" col="0">
                  <v-template>
                    <Label :text="item.name"/>
                  </v-template>
                </ListView>
              </GridLayout>
            </GridLayout>
    
            // [...] possibly other stuff
    
        </template>
  1. Finally, in the script section, add this
        <script lang="ts">
        import Vue from "vue";
        import { gql } from "apollo-boost";
        import * as queries from "../../graphql/queries";
        import * as ApplicationSettings from "tns-core-modules/application-settings";

        export default {
          data() {
            return {
              getItems: [],
            };
          },
          apollo: {
            getItems: {
              // prefetch: true,
              query: queries.GET_ITEMS,
              update({ getItems }) {
                return getItems;
              }
            }
          }
        }
        </script>
  1. Try out and hopefully you are happy that it works perfectly fine :)

Please remember: The paths also might have to be adjusted to your personal solution.

I hope this helps someone :)

Upvotes: 1

Cem Kaan
Cem Kaan

Reputation: 2236

I have been using Vue-apollo with nativescript-vue last 2 months.

Step by step apollo installation with JWT

  1. Use vue-apollo manual installation yarn add vue-apollo graphql apollo-boost
  2. Create apollo.config.jsfile
  3. add apollo code to your main.ts file
import Vue from 'nativescript-vue'
import List from './components/List.vue'
import Login from './components/Login.vue'
import * as ApplicationSettings from "tns-core-modules/application-settings";
import VueDevtools from 'nativescript-vue-devtools'
import VueApollo from "vue-apollo";
import {
    ApolloClient,
    InMemoryCache,
    HttpLink,
    ApolloLink
} from "apollo-boost";
import { onError } from "apollo-link-error";
import { setContext } from "apollo-link-context";
/////////////// APOLLO
Vue.use(VueApollo);
const errorLink = onError(({ graphQLErrors }) => {
    if (graphQLErrors) graphQLErrors.map(({ message }) => console.log(message));
});
const httpLink = new HttpLink({
    uri: "https://polar-badlands-01357.herokuapp.com/graphql"
});
const authLink = setContext((_, { headers }) => {
    // get the authentication token from ApplicationSettings if it exists
    var tokenInAppSettings = ApplicationSettings.getString("token");
    // return the headers to the context so HTTP link can read them
    return {
        headers: {
            ...headers,
            authorization: tokenInAppSettings
                ? `Bearer ${tokenInAppSettings}`
                : null
        }
    };
});
export const apolloClient = new ApolloClient({
    link: ApolloLink.from([errorLink, authLink, httpLink]),
    cache: new InMemoryCache()
});

const apolloProvider = new VueApollo({
    defaultClient: apolloClient
});


if(TNS_ENV !== 'production') {
  Vue.use(VueDevtools)
}
import store from './store'

// Prints Vue logs when --env.production is *NOT* set while building
Vue.config.silent = true

new Vue({
  store,
  apolloProvider,
  render: h => h("frame", [h(ApplicationSettings.hasKey("token")? List : Login)])
}).$start()

If someone is interested please check this complete Github repo with login and mutation examples.

And for a complete tested nativescript-vue plugin database check out plug-in page

Upvotes: 1

jawahar
jawahar

Reputation: 85

Plugins work as in any other NativeScript app, but you may wonder how UI plugins work with Vue.

UI plugins work almost identically to how you'd use a NativeScript UI plugin in an Angular app.

According to the document's description plugins might work out-of-box expect for UI components which we have to register. I personally did use not vue-apollo but i hoping to work in nativescript-vue.

Upvotes: 0

Related Questions