This tutorial demonstrates how to utilize the GraphQL API through NodeJS at a basic level. Familiarity with basic Linux shell commands, NodeJS, NPM, TypeScript, JavaScript, and GraphQL is assumed.
-
Initiate a new NPM project:
mkdir test-graphql-api cd test-graphql-api npm init # <press enter multiple times>
-
Install the necessary dependencies:
- TypeScript compiler.
- Lana-specific TypeScript GraphQL code generator.
- Lana-specific core library (provides GraphQL client helper library).
- Optionally, install the "cross-fetch" package if your older NodeJS version doesn't support the "fetch()" API.
npm install -D typescript @lana-commerce/core @lana-commerce/typescript-codegen cross-fetch
-
Initialize TypeScript configuration:
npm exec -- tsc --init
-
Construct a directory with .graphql files. The TypeScript GraphQL code generator we utilize targets a dedicated directory:
mkdir graphql echo "query GetCountriesInfo { infoCountries { code name } }" > graphql/all.graphql
-
Generate types and queries as TypeScript code using the TypeScript GraphQL code generator:
npm exec -- lana-commerce-typescript-codegen graphql graphql
The execution should result in the creation of the following files:
graphql/ ├── all.graphql ├── fragments ├── operations │ └── GetCountriesInfoQuery.ts └── types.ts
-
Create a basic script and save it as
main.ts
:import "cross-fetch/polyfill"; // only if your NodeJS doesn't have "fetch()" API import { request, prettyPrintRequestResponseError } from "@lana-commerce/core/request"; import getCountriesInfoQuery from "./graphql/operations/GetCountriesInfoQuery"; async function main() { const response = await request(getCountriesInfoQuery)(); if (response.kind !== "data") { throw new Error(prettyPrintRequestResponseError(response)); } for (const c of response.data) { console.log(`CODE: ${c.code}, NAME: ${c.name}`); } } main();
-
Compile and execute the script:
npm exec -- tsc node main.js
If successful, the script will print a list of countries:
CODE: AD, NAME: Andorra CODE: AE, NAME: United Arab Emirates CODE: AF, NAME: Afghanistan CODE: AG, NAME: Antigua and Barbuda ... CODE: YT, NAME: Mayotte CODE: ZA, NAME: South Africa CODE: ZM, NAME: Zambia CODE: ZW, NAME: Zimbabwe
-
Congratulations! You have written a simple script that uses the Lana GraphQL API. The subsequent steps are optional.
-
To add some complexity, try a query with variables. Append the following query to the
graphql/all.graphql
file:query GetProvinces($countryCode: String!) { infoProvinces(country_code: $countryCode) { code name } }
-
Generate types and queries once more:
npm exec -- lana-commerce-typescript-codegen graphql graphql
-
Modify the
main.ts
script by incorporating an import statement for our new query:import getProvincesQuery from "./graphql/operations/GetProvincesQuery";
-
Further modify the
main.ts
script by appending the following code at the conclusion of themain()
function:const response2 = await request(getProvincesQuery)({ countryCode: "XX" }); if (response2.kind !== "data") { throw new Error(prettyPrintRequestResponseError(response2, true)); } for (const p of response2.data) { console.log(`PROVINCE CODE: ${p.code}, NAME: ${p.name}`); }
Note that a non-existent country is used intentionally here. Compiling and running this script will yield an error. Also, a
detailed
flag was set totrue
in a call toprettyPrintRequestResponseError()
. This should provide more detailed error information. -
Compile and execute the script:
npm exec -- tsc node main.js
In addition to your countries list, an exception should be thrown, with a message resembling this:
Error: GraphQL API request failed: Url: https://api.lana.dev/storefront.json IdempotencyKey: 51717fea-d16e-4455-9f93-3892852cfac3 Operation: query GetProvinces($countryCode:String!){infoProvinces(country_code:$countryCode){code name}} Variables: { "countryCode": "XX" } [NotFound] Not Found
-
Feel free to modify the country code to a valid one and try the process again. Remember to compile your code before executing it!
-
This concludes the tutorial.
Commerce or Storefront API
This tutorial implicitly employs the Storefront API as it is the default when working with the mentioned libraries. If you wish to work with the Commerce API, you need to make the following modifications:
-
When generating GraphQL TypeScript code, explicitly provide the schema URL:
npm exec -- lana-commerce-typescript-codegen graphql \ --schema https://docs.lana.dev/api/commerce-schema.graphql graphql
-
When making API calls using the
request()
function, provide the appropriate option:const response = await request(getCountriesInfoQuery)(undefined, { commerce: true });