Connecting to a Service
View in PortugueseThis content was migrated from the VTEX Learning Center and is no longer being actively maintained. For the most accurate and up-to-date information, please check the official documentation.
Introduction
An admin app ends up losing its meaning if it cannot consume data. So, in the last step of the course, we will learn how to connect your admin app to a service and then use it in the front-end of the application.
Activity
- Start by adding the required builders for service:
/manifest.json
_11{_11 ..._11 "builders": {_11 "react": "3.x",_11 "messages": "1.x",_11 "docs": "0.x",_11 "admin": "0.x",_11+ "node": "6.x",_11+ "graphql": "1.x"_11 }_11}
- Create a
graphql/folder and add a simpleschema.graphqlfile with a single query:
/graphql/schema.graphql
_10type Query {_10 helloworld: String_10}
- Create a
node/folder and add anindex.tsfile to it that will instantiate our service:
/node/index.ts
_11import { Service } from '@vtex/api'_11_11export default new Service({_11 graphql: {_11 resolvers: {_11 Query: {_11 helloworld: () => `Service number: ${Math.random()}`,_11 },_11 },_11 },_11})
Our service will then, in the query helloworld, return a random number.
- In the
/nodefolder so that you can develop well locally, you will need apackage.json, you can add a simple one:
/node/package.json
_21{_21 "dependencies": {_21 "co-body": "^6.0.0",_21 "ramda": "^0.25.0"_21 },_21 "devDependencies": {_21 "@types/co-body": "^0.0.3",_21 "@types/jest": "^24.0.18",_21 "@types/node": "^12.0.0",_21 "@types/ramda": "types/npm-ramda#dist",_21 "@vtex/api": "6.36.2",_21 "@vtex/test-tools": "^1.0.0",_21 "tslint": "^5.14.0",_21 "tslint-config-vtex": "^2.1.0",_21 "typescript": "3.8.3"_21 },_21 "scripts": {_21 "lint": "tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'"_21 },_21 "version": "0.0.7"_21}
- In the
react/folder we will need to define a query to be able to use the resolver that we defined in the service. To do this, create agraphql/folder inside thereact/folder and in this folder, create ahelloworld.gqlwith:
/react/graphql/helloworld.gql:
_10query hello {_10 helloworld_10}
- Finally, we need to add this query to our component in
adminExample.ts
_20import React, { FC } from 'react'_20import { Layout, PageBlock } from 'vtex.styleguide'_20+import { useQuery } from 'react-apollo'_20_20+import helloworld from './graphql/helloworld.gql'_20_20const AdminExample: FC = () => {_20+ const { data } = useQuery(helloworld)_20_20 return (_20 <Layout>_20 <PageBlock title="Title" subtitle="Some explanation." variation="full">_20 <h1>Hello, World!</h1>_20+ <p>{data?.helloworld}</p>_20 </PageBlock>_20 </Layout>_20 )_20}_20_20export default AdminExample
The result should be:
