From fdaa54c9bbf83e92559971867a52089cacfc4d7f Mon Sep 17 00:00:00 2001 From: Anil Kumar Date: Thu, 6 May 2021 10:57:03 +0200 Subject: [PATCH 1/9] Add GraphQL TypeScript SDK getting started example --- docs/sdk/api/graphQLTypescriptSdk.md | 142 +++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 docs/sdk/api/graphQLTypescriptSdk.md diff --git a/docs/sdk/api/graphQLTypescriptSdk.md b/docs/sdk/api/graphQLTypescriptSdk.md new file mode 100644 index 000000000..6419cbf6b --- /dev/null +++ b/docs/sdk/api/graphQLTypescriptSdk.md @@ -0,0 +1,142 @@ +## Getting started +This tutorial will show you how to use the middlewares in this **[commercetools Typescript SDK](https://github.com/commercetools/commercetools-sdk-typescript/)** and **[GraphQL API](https://docs.commercetools.com/api/graphql)** to get a simple commercetools Javascript app running. + +### Create a API client +[Create API client](https://docs.commercetools.com/tutorials/getting-started#creating-an-api-client) from Merchant Center. If you do not have account [follow the steps to create a free trial account](https://docs.commercetools.com/tutorials/getting-started#first-steps). +In this guide we’ll be calling a method of commercetools API using TypeScript SDK and GraphQL API to get the settings of a commercetools project. The commercetools API is the foundation of the commercetools Platform, and almost every commercetools client app uses it. Aside from getting project information, the commercetools API allows clients to call methods that can be used for everything from creating products to updating an order’s status. Before we can call any methods, we need to configure our new app to obtain an access token. + +### Getting a client credentials to use the commercetools API +From the API client Details page mentioned in the previous step copy `project_key`, `client_id`, `secret`, `API URL`, `scope` and `Auth URL`. The commercetools API uses `client_id` and `secret` to authenticate the requests your app makes. In a later step, you’ll be asked to use these values in your code. + +### Set up your local project +If you don’t already have a project, let’s create a new one. In an empty directory, you can initialize a new project using the following command: + +``` +$ npm init -y +``` + +After you’re done, you’ll have a new package.json file in your directory. +Install the `@commercetools/sdk-client`, `@commercetools/sdk-middleware-auth`, `@commercetools/sdk-middleware-http`, `@commercetools/typescript-sdk` and `dotenv` packages and save it to your `package.json` dependencies using the following command: + +``` +$ npm install @commercetools/sdk-client @commercetools/sdk-middleware-auth @commercetools/sdk-middleware-http @commercetools/typescript-sdk dotenv +``` + +Create a new file called `project.js` in this directory and add the following code: +```js +const { createClient } = require('@commercetools/sdk-client') +const { createAuthMiddlewareForClientCredentialsFlow } = require('@commercetools/sdk-middleware-auth') +const { createHttpMiddleware } = require('@commercetools/sdk-middleware-http') +const { createApiBuilderFromCtpClient } = require("@commercetools/typescript-sdk"); + +const fetch = require('node-fetch') +require('dotenv').config() + +console.log('Getting started with commercetools Typescript SDK and GraphQL API'); +``` + +Back at the command line, run the program using the following command: +``` +$ node project.js +Getting started with commercetools Typescript SDK and GraphQL API +``` +If you see the same output as above, we’re ready to start. + +### Get commercetools project settings with the commercetools API +In this guide we’ll get project settings information. We’ll also follow the best practice of keeping secrets outside of your code (do not hardcode sensitive data). + +Store the **client_id** and **secret** in a new environment variable. Create a new file called `.env` in this directory and add the following code: + +``` +ADMIN_CLIENT_ID= +ADMIN_CLIENT_SECRET= +``` +Replace the values with your `client_id` and `secret` that you copied earlier. + +Re-open `project.js` and add the following code: +```js +const { + ADMIN_CLIENT_ID, + ADMIN_CLIENT_SECRET, +} = process.env; + +const projectKey = '' + +// Create a httpMiddleware for the your project AUTH URL +const authMiddleware = createAuthMiddlewareForClientCredentialsFlow({ + host: '', + projectKey, + credentials: { + clientId: ADMIN_CLIENT_ID, + clientSecret: ADMIN_CLIENT_SECRET, + }, + scopes: [''], + fetch, +}) + +// Create a httpMiddleware for the your project API URL +const httpMiddleware = createHttpMiddleware({ + host: '', + fetch, +}) + +// Create a client using authMiddleware and httpMiddleware +const client = createClient({ + middlewares: [authMiddleware, httpMiddleware], +}) + +// Create a API root from API builder of commercetools platform client +const apiRoot = createApiBuilderFromCtpClient(client) + +// GraphQL query to get commercetools project settings +const projectSettingsQuery = ` + query { + project { + name + languages + currencies + countries + version + createdAt + } + } +` + +(async () => { + try { + await apiRoot.withProjectKey({projectKey}).graphql() + .post({ + body : { + query: projectSettingsQuery, + variables: {} + } + }) + .execute() + .then(data => { + console.log('Project information --->', data); + }) + .catch(error => { + console.log('ERROR --->', error); + }) + } catch (error) { + console.log('ERROR --->', error); + } +})() +``` +Replace the value ``, ``, `` and `` with your client `project_key`, `API URL`, `scope`, and `Auth URL` that you copied earlier. + +This code creates a **client**, which uses `authMiddleware` and `httpMiddleware`. The `httpMiddleware` reads the `client_id` and `secret` from environment variables. Then client will **execute** get project information request from `apiRoot` using **TypeScript SDK** and **GraphQL** query[projectSettingsQuery] to get project settings. `projectSettingsQuery` retrieves project's `name`, `languages`,`currencies`,`countries`, `version` and `createdAt` fields. To explore commercetools GraphQL API you can use an interactive [GraphiQL environment](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) which is available as a part of our [ImpEx & API Playground](https://docs.commercetools.com/docs/login). + +Run the program. The output should look like the following if the request is successful: +``` +$ node project.js +Getting started with commercetools Typescript SDK and GraphQL API +Project information ---> { + body: { + data: { + project: + } + }, + statusCode: 200 +} +``` From f782d787e41d46161e8d69aaac0063471967bab0 Mon Sep 17 00:00:00 2001 From: Anil Kumar Date: Thu, 6 May 2021 15:37:31 +0200 Subject: [PATCH 2/9] Add GraphQL mutation example --- docs/sdk/api/graphQLTypescriptSdk.md | 177 +++++++++++++++++++++++++++ 1 file changed, 177 insertions(+) diff --git a/docs/sdk/api/graphQLTypescriptSdk.md b/docs/sdk/api/graphQLTypescriptSdk.md index 6419cbf6b..363c8c7ad 100644 --- a/docs/sdk/api/graphQLTypescriptSdk.md +++ b/docs/sdk/api/graphQLTypescriptSdk.md @@ -140,3 +140,180 @@ Project information ---> { statusCode: 200 } ``` + +### Next Steps +You just built your first commercetools Javascript app with TypeScript SDK and GraphQL API! 🥳🎉 + +There’s plenty more to learn and explore about this TypeScript SDK and the commercetools platform. Here are some advanced tutorials: +- [Create a new customer using GraphQL mutation and TypeScript SDK](#create-a-new-customer) +- [How to use where clause with GraphQL query using TypeScript SDK](#how-to-use-graphql-where-clause) + + + +## Create a new Customer +This tutorial will show you how to create a new customer using **[commercetools Typescript SDK](https://github.com/commercetools/commercetools-sdk-typescript/)** and **[GraphQL](https://docs.commercetools.com/api/graphql)** on your commercetools project. You already finished [Getting started with TypeScript SDK and GraphQL](#getting-started) tutorials and basic project steps are not repeated here again. + +### Set up `customer.js` file +Create a new file called `customer.js` in your project root directory and add the following code: + +```js +const { createClient } = require('@commercetools/sdk-client') +const { createAuthMiddlewareForClientCredentialsFlow } = require('@commercetools/sdk-middleware-auth') +const { createHttpMiddleware } = require('@commercetools/sdk-middleware-http') +const { createApiBuilderFromCtpClient } = require("@commercetools/typescript-sdk"); + +const fetch = require('node-fetch') +require('dotenv').config() + +console.log('Create a new customer using GraphQL and TypeScript SDK'); +``` + +Nodejs dependencies `@commercetools/sdk-client`, `@commercetools/sdk-middleware-auth`,`@commercetools/sdk-middleware-http`, `@commercetools/typescript-sdk`, and `dotenv` are already installed as part of [Getting started with TypeScript SDK and GraphQL](../getting-started-with-graphql-ts-sdk/getting-started.md) tutorial. Back at the command line, run the program using the following command: +``` +$ node customer.js +Create a new customer using GraphQL and TypeScript SDK +``` +If you see the same output as above, we’re ready to start. + +### Create an API client +You already have API client from the [Getting started with TypeScript SDK and GraphQL](../getting-started-with-graphql-ts-sdk/getting-started.md) tutorial on `project.js` file. + +Re-open `customer.js` and add the following code: +```js +const { + ADMIN_CLIENT_ID, + ADMIN_CLIENT_SECRET, +} = process.env; + +const projectKey = '' + +// Create a httpMiddleware for the your project AUTH URL +const authMiddleware = createAuthMiddlewareForClientCredentialsFlow({ + host: '', + projectKey, + credentials: { + clientId: ADMIN_CLIENT_ID, + clientSecret: ADMIN_CLIENT_SECRET, + }, + scopes: [''], + fetch, +}) + +// Create a httpMiddleware for the your project API URL +const httpMiddleware = createHttpMiddleware({ + host: '', + fetch, +}) + +// Create a client using authMiddleware and httpMiddleware +const client = createClient({ + middlewares: [authMiddleware, httpMiddleware], +}) + +// Create a API root from API builder of commercetools platform client +const apiRoot = createApiBuilderFromCtpClient(client) + +``` +Replace the value ``, ``, `` and `` with your client `projectKey`, `hostAPI_URL`, `scopes`, and `host Auth_URL` values from `project.js` file. + +### Create GraphQL query and mutation +Add the following code to `customer.js`. + +```js +// New customer data +const createCustomerMutationVariable = { + "newCustomer": { + "email": "your.test@test.com", + "password": "123", + "firstName": "yourFirstName", + "lastName": "yourLastName" + } + }; + +// mutation to create new customer +const createCustomerMutation = ` + mutation createCustomer ($newCustomer: CustomerSignUpDraft!) { + customerSignUp (draft: $newCustomer) { + customer { + id + } + } + } +`; + +// GraphQL query to get Customer `email` and `firstName` +const getCustomerByIdQuery = ` + query ($id: String) { + customer (id: $id) { + email + firstName + } + } +`; +``` + +`createCustomerMutationVariable` contains the new customer data and mandatory field `email` and `password` and optional fields `firstName` and `lastName`. To find out list of all possible fields you can refer [CustomerDraft](https://docs.commercetools.com/api/projects/customers#customerdraft) documentation. Make sure you pass unique `email` value, you will get an error if try to create a new customer using already existing customer's email. + +`createCustomerMutation` is the GraphQL **mutation** to create a **new customer** on the commercetools project and returns `id`. + +`getCustomerByIdQuery` is the GraphQL **query** to get newly created customer info `email` and `firstName` by `id`. + +To explore commercetools GraphQL API you can use an interactive [GraphiQL environment](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) which is available as a part of [ImpEx & API Playground](https://docs.commercetools.com/docs/login). + +### Call API to create new Customer using TypeScript SDK and Graph API + +Add the following code to `customer.js`. +```js +// Create a new customer and return customer id +const createNewCustomer = async () => { + const result = await apiRoot.withProjectKey({projectKey}).graphql().post({ + body : { + query: CreateCustomerMutation, + variables: createCustomerMutationVariable, + } + }).execute() + + // Get customerId from the result + const { + body: { + data: { + customerSignUp: { + customer: { + id:customerId + } + } + } + } + } = result + + return customerId +} + +// Get customer's email and firstName by customer id +const getCustomerById = async (customerId) => apiRoot.withProjectKey({projectKey}).graphql().post({ + body: { + query: customerQuery, + variables: { + id: customerId + } + } + }) + .execute() + +(async () => { + try { + const newlyCreatedCustomerId = await createNewCustomer() + const newlyCreatedCustomer = await getCustomerById(newlyCreatedCustomerId) + console.log('Newly created customer info ---->', JSON.stringify(newlyCreatedCustomer)) + } catch (error) { + console.log('ERROR --->', error) + } +})() +``` + +Run the program. The output should look like the following if the request is successful: +``` +$ node customer.js +Create a new customer using GraphQL and TypeScript SDK +Newly created customer info ----> {"body":{"data":{"customer":{"email":"your.test@test.com","firstName":"yourFirstName"}}},"statusCode":200} +``` From e6baa5a0e49b107ec384e1670b5d3d854895cefb Mon Sep 17 00:00:00 2001 From: Anil Kumar Date: Fri, 7 May 2021 10:51:28 +0200 Subject: [PATCH 3/9] Add how to use where clause with GraphQL and TypeScript SDK --- docs/sdk/api/graphQLTypescriptSdk.md | 132 ++++++++++++++++++++++++++- 1 file changed, 128 insertions(+), 4 deletions(-) diff --git a/docs/sdk/api/graphQLTypescriptSdk.md b/docs/sdk/api/graphQLTypescriptSdk.md index 363c8c7ad..243ae7b33 100644 --- a/docs/sdk/api/graphQLTypescriptSdk.md +++ b/docs/sdk/api/graphQLTypescriptSdk.md @@ -144,14 +144,16 @@ Project information ---> { ### Next Steps You just built your first commercetools Javascript app with TypeScript SDK and GraphQL API! 🥳🎉 -There’s plenty more to learn and explore about this TypeScript SDK and the commercetools platform. Here are some advanced tutorials: +There’s plenty more to learn and explore about this TypeScript SDK and the commercetools platform. Here are some advanced tutorials and links: - [Create a new customer using GraphQL mutation and TypeScript SDK](#create-a-new-customer) -- [How to use where clause with GraphQL query using TypeScript SDK](#how-to-use-graphql-where-clause) +- [How to use where clause with GraphQL query using TypeScript SDK](#how-to-use-where-clause-with-graphql-query-using-typescript-sdk) +- [commercetools developer tutorials](https://docs.commercetools.com/tutorials/) +- [commercetools JS SDK training](https://github.com/commercetools/commercetools-js-sdk-v2-training) ## Create a new Customer -This tutorial will show you how to create a new customer using **[commercetools Typescript SDK](https://github.com/commercetools/commercetools-sdk-typescript/)** and **[GraphQL](https://docs.commercetools.com/api/graphql)** on your commercetools project. You already finished [Getting started with TypeScript SDK and GraphQL](#getting-started) tutorials and basic project steps are not repeated here again. +This tutorial will show you how to create a new customer using **[commercetools Typescript SDK](https://github.com/commercetools/commercetools-sdk-typescript/)** and **[GraphQL](https://docs.commercetools.com/api/graphql)** on your commercetools project. Assuming you already finished [Getting started with TypeScript SDK and GraphQL](#getting-started) tutorials and basic project steps are not repeated here again. ### Set up `customer.js` file Create a new file called `customer.js` in your project root directory and add the following code: @@ -260,7 +262,7 @@ const getCustomerByIdQuery = ` To explore commercetools GraphQL API you can use an interactive [GraphiQL environment](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) which is available as a part of [ImpEx & API Playground](https://docs.commercetools.com/docs/login). -### Call API to create new Customer using TypeScript SDK and Graph API +### Call API to create new Customer using TypeScript SDK and GraphQL API Add the following code to `customer.js`. ```js @@ -317,3 +319,125 @@ $ node customer.js Create a new customer using GraphQL and TypeScript SDK Newly created customer info ----> {"body":{"data":{"customer":{"email":"your.test@test.com","firstName":"yourFirstName"}}},"statusCode":200} ``` + + +## How to use where clause with GraphQL query using TypeScript SDK +This tutorial will show you how to use **where clause** with **[GraphQL query](https://docs.commercetools.com/api/graphql)** and **[commercetools Typescript SDK](https://github.com/commercetools/commercetools-sdk-typescript/)**. Assuming you already finished [Getting started with TypeScript SDK and GraphQL](#getting-started) tutorials and basic project steps are not repeated here again. + +### Set up `whereClauseQuery.js` file +Create a new file called `whereClauseQuery.js` in your project root directory and add the following code: + +```js +const { createClient } = require('@commercetools/sdk-client') +const { createAuthMiddlewareForClientCredentialsFlow } = require('@commercetools/sdk-middleware-auth') +const { createHttpMiddleware } = require('@commercetools/sdk-middleware-http') +const { createApiBuilderFromCtpClient } = require("@commercetools/typescript-sdk"); + +const fetch = require('node-fetch') +require('dotenv').config() + +console.log('where clause query with GraphQL and TypeScript SDK'); +``` + +Nodejs dependencies `@commercetools/sdk-client`, `@commercetools/sdk-middleware-auth`,`@commercetools/sdk-middleware-http`, `@commercetools/typescript-sdk`, and `dotenv` are already installed as part of [Getting started with TypeScript SDK and GraphQL](#getting-started) tutorial. Back at the command line, run the program using the following command: +``` +$ node whereClauseQuery.js +where clause query with GraphQL and TypeScript SDK +``` +If you see the same output as above, we’re ready to start. + +### Create an API client +You already have API client from the [Getting started with TypeScript SDK and GraphQL](#getting-started) tutorial on `project.js` file. +Re-open `whereClauseQuery.js` and add the following code: +```js +const { + ADMIN_CLIENT_ID, + ADMIN_CLIENT_SECRET, +} = process.env; + +const projectKey = '' + +// Create a httpMiddleware for the your project AUTH URL +const authMiddleware = createAuthMiddlewareForClientCredentialsFlow({ + host: '', + projectKey, + credentials: { + clientId: ADMIN_CLIENT_ID, + clientSecret: ADMIN_CLIENT_SECRET, + }, + scopes: [''], + fetch, +}) + +// Create a httpMiddleware for the your project API URL +const httpMiddleware = createHttpMiddleware({ + host: '', + fetch, +}) + +// Create a client using authMiddleware and httpMiddleware +const client = createClient({ + middlewares: [authMiddleware, httpMiddleware], +}) + +// Create a API root from API builder of commercetools platform client +const apiRoot = createApiBuilderFromCtpClient(client) + +``` +Replace the value ``, ``, `` and `` with your client `projectKey`, `host API_URL`, `scopes`, and `host Auth_URL` values from `project.js` file. + +### Create GraphQL query and mutation +Add the following code to `whereClauseQuery.js`. + +```js +// where clause with query by customer id +const whereClauseCustomerIdVariable = { + "where": "id=\"\"" + }; + +// GraphQL query to get customer `email` and `firstName` using where clause and customer id query predicate +const getCustomerByWhereClauseQuery = ` + query ($where: String) { + customers (where: $where) { + email + firstName + } + } +`; +``` + +`whereClauseCustomerIdVariable` contains where clause with value `"id=\"\""`. For details about `where` query refer [Query Predicates](https://docs.commercetools.com/api/predicates/query) documentation. Replace `` with your customer [id](https://docs.commercetools.com/api/general-concepts#identifier) for which you would like to retrieve customer `email` and `firstName`. + +`getCustomerByWhereClauseQuery` is the GraphQL **query** to get customer info `email` and `firstName` by using **where clause** and **customer id** query predicate. + +To explore commercetools GraphQL API you can use an interactive [GraphiQL environment](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) which is available as a part of [ImpEx & API Playground](https://docs.commercetools.com/docs/login). + +### Call API to get customer information using TypeScript SDK and GraphQL + +Add the following code to `whereClauseQuery.js`. +```js +// Get customer's email and firstName by customer id +const getCustomerByWhereClause = async () => apiRoot.withProjectKey({projectKey}).graphql().post({ + body: { + query: getCustomerByWhereClauseQuery, + variables: whereClauseCustomerIdVariable + } + }) + .execute() + +(async () => { + try { + const result = await getCustomerByWhereClause() + console.log('Customer info ---->', JSON.stringify(result)) + } catch (error) { + console.log('ERROR --->', error) + } +})() +``` + +Run the program. The output should look like the following if the request is successful: +``` +$ node whereClauseQuery.js +where clause query with GraphQL and TypeScript SDK +Customer info ----> {"body":{"data":{"customer":{"email":"your.test@test.com","firstName":"yourFirstName"}}},"statusCode":200} +``` From b676bd362278ee14556f4748999b31d4528d87a9 Mon Sep 17 00:00:00 2001 From: Anil Kumar Date: Mon, 7 Jun 2021 17:11:11 +0200 Subject: [PATCH 4/9] Update the getting started TypeScript and graphQL example --- docs/sdk/api/graphQLTypescriptSdk.md | 122 ++++++++++++--------------- 1 file changed, 53 insertions(+), 69 deletions(-) diff --git a/docs/sdk/api/graphQLTypescriptSdk.md b/docs/sdk/api/graphQLTypescriptSdk.md index 243ae7b33..a49bca0d2 100644 --- a/docs/sdk/api/graphQLTypescriptSdk.md +++ b/docs/sdk/api/graphQLTypescriptSdk.md @@ -3,10 +3,7 @@ This tutorial will show you how to use the middlewares in this **[commercetools ### Create a API client [Create API client](https://docs.commercetools.com/tutorials/getting-started#creating-an-api-client) from Merchant Center. If you do not have account [follow the steps to create a free trial account](https://docs.commercetools.com/tutorials/getting-started#first-steps). -In this guide we’ll be calling a method of commercetools API using TypeScript SDK and GraphQL API to get the settings of a commercetools project. The commercetools API is the foundation of the commercetools Platform, and almost every commercetools client app uses it. Aside from getting project information, the commercetools API allows clients to call methods that can be used for everything from creating products to updating an order’s status. Before we can call any methods, we need to configure our new app to obtain an access token. - -### Getting a client credentials to use the commercetools API -From the API client Details page mentioned in the previous step copy `project_key`, `client_id`, `secret`, `API URL`, `scope` and `Auth URL`. The commercetools API uses `client_id` and `secret` to authenticate the requests your app makes. In a later step, you’ll be asked to use these values in your code. +In this guide, we’ll be calling a method of commercetools API using TypeScript SDK and GraphQL API to get the settings of a commercetools project. The commercetools API is the foundation of the commercetools platform, and almost every commercetools client app uses it. Aside from getting project information, the commercetools API allows clients to call methods that can be used for everything from creating products to updating an order’s status. Before we can call any methods, we need to configure our new app to obtain an access token. ### Set up your local project If you don’t already have a project, let’s create a new one. In an empty directory, you can initialize a new project using the following command: @@ -14,80 +11,69 @@ If you don’t already have a project, let’s create a new one. In an empty dir ``` $ npm init -y ``` - After you’re done, you’ll have a new package.json file in your directory. -Install the `@commercetools/sdk-client`, `@commercetools/sdk-middleware-auth`, `@commercetools/sdk-middleware-http`, `@commercetools/typescript-sdk` and `dotenv` packages and save it to your `package.json` dependencies using the following command: -``` -$ npm install @commercetools/sdk-client @commercetools/sdk-middleware-auth @commercetools/sdk-middleware-http @commercetools/typescript-sdk dotenv -``` +#### Getting client credentials to use the commercetools API +Create a new file called `.env` in this directory. Select **Environment Variables (.env)** in the dropdown on the API client details page mentioned in the previous step and copy client credentials to the `.env` file. Should have values for these variables `CTP_PROJECT_KEY`, `CTP_CLIENT_SECRET`, `CTP_CLIENT_ID`, `CTP_AUTH_URL`, `CTP_API_URL` and `CTP_SCOPES`. Create a new file called `project.js` in this directory and add the following code: ```js -const { createClient } = require('@commercetools/sdk-client') -const { createAuthMiddlewareForClientCredentialsFlow } = require('@commercetools/sdk-middleware-auth') -const { createHttpMiddleware } = require('@commercetools/sdk-middleware-http') -const { createApiBuilderFromCtpClient } = require("@commercetools/typescript-sdk"); - -const fetch = require('node-fetch') -require('dotenv').config() + const { createClient } = require('@commercetools/sdk-client') + const { createAuthMiddlewareForClientCredentialsFlow } = require('@commercetools/sdk-middleware-auth') + const { createHttpMiddleware } = require('@commercetools/sdk-middleware-http') + const { createApiBuilderFromCtpClient } = require("@commercetools/typescript-sdk") + const fetch = require('node-fetch') + require('dotenv').config() + //reference API client credentials from environment variables + const { + CTP_PROJECT_KEY, + CTP_CLIENT_SECRET, + CTP_CLIENT_ID, + CTP_AUTH_URL, + CTP_API_URL, + CTP_SCOPES, + } = process.env + const projectKey = CTP_PROJECT_KEY + const authMiddleware = createAuthMiddlewareForClientCredentialsFlow({ + host: CTP_AUTH_URL, + projectKey, + credentials: { + clientId: CTP_CLIENT_ID, + clientSecret: CTP_CLIENT_SECRET, + }, + scopes: [CTP_SCOPES], fetch, + }) + const httpMiddleware = createHttpMiddleware({ + host: CTP_API_URL, + fetch, + }) + const client = createClient({ + middlewares: [authMiddleware, httpMiddleware], + }) + // Create an API root from API builder of commercetools platform client + const apiRoot = createApiBuilderFromCtpClient(client); + console.log('Getting started with commercetools Typescript SDK and GraphQL API'); +``` +This code creates a **client**, which uses `authMiddleware` and `httpMiddleware`. The `httpMiddleware` reads the `clientId` and `clientSecret` from environment variables. + +Install the `@commercetools/sdk-client`, `@commercetools/sdk-middleware-auth`, `@commercetools/sdk-middleware-http`, `@commercetools/typescript-sdk` and `dotenv` packages and save it to your `package.json` dependencies using the following command: -console.log('Getting started with commercetools Typescript SDK and GraphQL API'); +``` +$ npm install @commercetools/sdk-client @commercetools/sdk-middleware-auth @commercetools/sdk-middleware-http @commercetools/typescript-sdk dotenv ``` -Back at the command line, run the program using the following command: +Run the program using the following command: ``` $ node project.js Getting started with commercetools Typescript SDK and GraphQL API ``` If you see the same output as above, we’re ready to start. -### Get commercetools project settings with the commercetools API -In this guide we’ll get project settings information. We’ll also follow the best practice of keeping secrets outside of your code (do not hardcode sensitive data). - -Store the **client_id** and **secret** in a new environment variable. Create a new file called `.env` in this directory and add the following code: - -``` -ADMIN_CLIENT_ID= -ADMIN_CLIENT_SECRET= -``` -Replace the values with your `client_id` and `secret` that you copied earlier. +### Get commercetools project settings with the commercetools GraphQL API +In this guide, we’ll get project settings information using commercetools GraphQL API. Re-open `project.js` and add the following code: ```js -const { - ADMIN_CLIENT_ID, - ADMIN_CLIENT_SECRET, -} = process.env; - -const projectKey = '' - -// Create a httpMiddleware for the your project AUTH URL -const authMiddleware = createAuthMiddlewareForClientCredentialsFlow({ - host: '', - projectKey, - credentials: { - clientId: ADMIN_CLIENT_ID, - clientSecret: ADMIN_CLIENT_SECRET, - }, - scopes: [''], - fetch, -}) - -// Create a httpMiddleware for the your project API URL -const httpMiddleware = createHttpMiddleware({ - host: '', - fetch, -}) - -// Create a client using authMiddleware and httpMiddleware -const client = createClient({ - middlewares: [authMiddleware, httpMiddleware], -}) - -// Create a API root from API builder of commercetools platform client -const apiRoot = createApiBuilderFromCtpClient(client) - // GraphQL query to get commercetools project settings const projectSettingsQuery = ` query { @@ -100,7 +86,7 @@ const projectSettingsQuery = ` createdAt } } -` +`; (async () => { try { @@ -121,14 +107,13 @@ const projectSettingsQuery = ` } catch (error) { console.log('ERROR --->', error); } -})() +})(); ``` -Replace the value ``, ``, `` and `` with your client `project_key`, `API URL`, `scope`, and `Auth URL` that you copied earlier. - -This code creates a **client**, which uses `authMiddleware` and `httpMiddleware`. The `httpMiddleware` reads the `client_id` and `secret` from environment variables. Then client will **execute** get project information request from `apiRoot` using **TypeScript SDK** and **GraphQL** query[projectSettingsQuery] to get project settings. `projectSettingsQuery` retrieves project's `name`, `languages`,`currencies`,`countries`, `version` and `createdAt` fields. To explore commercetools GraphQL API you can use an interactive [GraphiQL environment](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) which is available as a part of our [ImpEx & API Playground](https://docs.commercetools.com/docs/login). +Then the client will **execute** get project information request from `apiRoot` using **TypeScript SDK** and **GraphQL** query[projectSettingsQuery] to get project settings. `projectSettingsQuery` retrieves project's `name`, `languages`,`currencies`,`countries`, `version` and `createdAt` fields. To explore commercetools GraphQL API, you can use an interactive [GraphiQL environment](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) available as a part of our [ImpEx & API Playground](https://docs.commercetools.com/docs/login). Run the program. The output should look like the following if the request is successful: -``` + +```shell $ node project.js Getting started with commercetools Typescript SDK and GraphQL API Project information ---> { @@ -146,12 +131,11 @@ You just built your first commercetools Javascript app with TypeScript SDK and G There’s plenty more to learn and explore about this TypeScript SDK and the commercetools platform. Here are some advanced tutorials and links: - [Create a new customer using GraphQL mutation and TypeScript SDK](#create-a-new-customer) -- [How to use where clause with GraphQL query using TypeScript SDK](#how-to-use-where-clause-with-graphql-query-using-typescript-sdk) +- [How to use where clause with GraphQL query using TypeScript SDK](#how-to-use-where-clause-with-graphql-query-using-typescript-sdk) - [commercetools developer tutorials](https://docs.commercetools.com/tutorials/) - [commercetools JS SDK training](https://github.com/commercetools/commercetools-js-sdk-v2-training) - ## Create a new Customer This tutorial will show you how to create a new customer using **[commercetools Typescript SDK](https://github.com/commercetools/commercetools-sdk-typescript/)** and **[GraphQL](https://docs.commercetools.com/api/graphql)** on your commercetools project. Assuming you already finished [Getting started with TypeScript SDK and GraphQL](#getting-started) tutorials and basic project steps are not repeated here again. From 37e3883a4af96779188e2ac14737c347574554e9 Mon Sep 17 00:00:00 2001 From: Anil Kumar Date: Mon, 7 Jun 2021 17:38:44 +0200 Subject: [PATCH 5/9] Update Create a new Customer using commercetools GraphQL API and TypeScript SDK tutorial --- docs/sdk/api/graphQLTypescriptSdk.md | 97 ++++++++++++---------------- 1 file changed, 42 insertions(+), 55 deletions(-) diff --git a/docs/sdk/api/graphQLTypescriptSdk.md b/docs/sdk/api/graphQLTypescriptSdk.md index a49bca0d2..3d771e685 100644 --- a/docs/sdk/api/graphQLTypescriptSdk.md +++ b/docs/sdk/api/graphQLTypescriptSdk.md @@ -136,7 +136,7 @@ There’s plenty more to learn and explore about this TypeScript SDK and the com - [commercetools JS SDK training](https://github.com/commercetools/commercetools-js-sdk-v2-training) -## Create a new Customer +## Create a new Customer using commercetools GraphQL API and TypeScript SDK This tutorial will show you how to create a new customer using **[commercetools Typescript SDK](https://github.com/commercetools/commercetools-sdk-typescript/)** and **[GraphQL](https://docs.commercetools.com/api/graphql)** on your commercetools project. Assuming you already finished [Getting started with TypeScript SDK and GraphQL](#getting-started) tutorials and basic project steps are not repeated here again. ### Set up `customer.js` file @@ -144,17 +144,42 @@ Create a new file called `customer.js` in your project root directory and add th ```js const { createClient } = require('@commercetools/sdk-client') -const { createAuthMiddlewareForClientCredentialsFlow } = require('@commercetools/sdk-middleware-auth') -const { createHttpMiddleware } = require('@commercetools/sdk-middleware-http') -const { createApiBuilderFromCtpClient } = require("@commercetools/typescript-sdk"); - -const fetch = require('node-fetch') -require('dotenv').config() - -console.log('Create a new customer using GraphQL and TypeScript SDK'); + const { createAuthMiddlewareForClientCredentialsFlow } = require('@commercetools/sdk-middleware-auth') + const { createHttpMiddleware } = require('@commercetools/sdk-middleware-http') + const { createApiBuilderFromCtpClient } = require("@commercetools/typescript-sdk") + const fetch = require('node-fetch') + require('dotenv').config() + //reference API client credentials from environment variables + const { + CTP_PROJECT_KEY, + CTP_CLIENT_SECRET, + CTP_CLIENT_ID, + CTP_AUTH_URL, + CTP_API_URL, + CTP_SCOPES, + } = process.env + const projectKey = CTP_PROJECT_KEY + const authMiddleware = createAuthMiddlewareForClientCredentialsFlow({ + host: CTP_AUTH_URL, + projectKey, + credentials: { + clientId: CTP_CLIENT_ID, + clientSecret: CTP_CLIENT_SECRET, + }, + scopes: [CTP_SCOPES], fetch, + }) + const httpMiddleware = createHttpMiddleware({ + host: CTP_API_URL, + fetch, + }) + const client = createClient({ + middlewares: [authMiddleware, httpMiddleware], + }) + // Create an API root from API builder of commercetools platform client + const apiRoot = createApiBuilderFromCtpClient(client); + console.log('Create a new customer using GraphQL and TypeScript SDK'); ``` - -Nodejs dependencies `@commercetools/sdk-client`, `@commercetools/sdk-middleware-auth`,`@commercetools/sdk-middleware-http`, `@commercetools/typescript-sdk`, and `dotenv` are already installed as part of [Getting started with TypeScript SDK and GraphQL](../getting-started-with-graphql-ts-sdk/getting-started.md) tutorial. Back at the command line, run the program using the following command: +Environment variables and Nodejs dependencies `@commercetools/sdk-client`, `@commercetools/sdk-middleware-auth`,`@commercetools/sdk-middleware-http`, `@commercetools/typescript-sdk`, and `dotenv` are already installed as part of [Getting started with TypeScript SDK and GraphQL](../getting-started-with-graphql-ts-sdk/getting-started.md) tutorial. Back at the command line, run the program using the following command: ``` $ node customer.js Create a new customer using GraphQL and TypeScript SDK @@ -164,44 +189,6 @@ If you see the same output as above, we’re ready to start. ### Create an API client You already have API client from the [Getting started with TypeScript SDK and GraphQL](../getting-started-with-graphql-ts-sdk/getting-started.md) tutorial on `project.js` file. -Re-open `customer.js` and add the following code: -```js -const { - ADMIN_CLIENT_ID, - ADMIN_CLIENT_SECRET, -} = process.env; - -const projectKey = '' - -// Create a httpMiddleware for the your project AUTH URL -const authMiddleware = createAuthMiddlewareForClientCredentialsFlow({ - host: '', - projectKey, - credentials: { - clientId: ADMIN_CLIENT_ID, - clientSecret: ADMIN_CLIENT_SECRET, - }, - scopes: [''], - fetch, -}) - -// Create a httpMiddleware for the your project API URL -const httpMiddleware = createHttpMiddleware({ - host: '', - fetch, -}) - -// Create a client using authMiddleware and httpMiddleware -const client = createClient({ - middlewares: [authMiddleware, httpMiddleware], -}) - -// Create a API root from API builder of commercetools platform client -const apiRoot = createApiBuilderFromCtpClient(client) - -``` -Replace the value ``, ``, `` and `` with your client `projectKey`, `hostAPI_URL`, `scopes`, and `host Auth_URL` values from `project.js` file. - ### Create GraphQL query and mutation Add the following code to `customer.js`. @@ -209,7 +196,7 @@ Add the following code to `customer.js`. // New customer data const createCustomerMutationVariable = { "newCustomer": { - "email": "your.test@test.com", + "email": "your.test-1@test.com", "password": "123", "firstName": "yourFirstName", "lastName": "yourLastName" @@ -254,7 +241,7 @@ Add the following code to `customer.js`. const createNewCustomer = async () => { const result = await apiRoot.withProjectKey({projectKey}).graphql().post({ body : { - query: CreateCustomerMutation, + query: createCustomerMutation, variables: createCustomerMutationVariable, } }).execute() @@ -273,18 +260,18 @@ const createNewCustomer = async () => { } = result return customerId -} +}; // Get customer's email and firstName by customer id const getCustomerById = async (customerId) => apiRoot.withProjectKey({projectKey}).graphql().post({ body: { - query: customerQuery, + query: getCustomerByIdQuery, variables: { id: customerId } } }) - .execute() + .execute(); (async () => { try { @@ -294,7 +281,7 @@ const getCustomerById = async (customerId) => apiRoot.withProjectKey({projectKey } catch (error) { console.log('ERROR --->', error) } -})() +})(); ``` Run the program. The output should look like the following if the request is successful: From 05190241bd12d84447583afeaa5e6e87afd93afa Mon Sep 17 00:00:00 2001 From: Anil Kumar Date: Mon, 7 Jun 2021 22:13:45 +0200 Subject: [PATCH 6/9] Update whereClauseQuery tutorial docs --- docs/sdk/api/graphQLTypescriptSdk.md | 84 ++++++++++++---------------- 1 file changed, 35 insertions(+), 49 deletions(-) diff --git a/docs/sdk/api/graphQLTypescriptSdk.md b/docs/sdk/api/graphQLTypescriptSdk.md index 3d771e685..b556d13d1 100644 --- a/docs/sdk/api/graphQLTypescriptSdk.md +++ b/docs/sdk/api/graphQLTypescriptSdk.md @@ -300,62 +300,48 @@ Create a new file called `whereClauseQuery.js` in your project root directory an ```js const { createClient } = require('@commercetools/sdk-client') -const { createAuthMiddlewareForClientCredentialsFlow } = require('@commercetools/sdk-middleware-auth') -const { createHttpMiddleware } = require('@commercetools/sdk-middleware-http') -const { createApiBuilderFromCtpClient } = require("@commercetools/typescript-sdk"); - -const fetch = require('node-fetch') -require('dotenv').config() - -console.log('where clause query with GraphQL and TypeScript SDK'); -``` - -Nodejs dependencies `@commercetools/sdk-client`, `@commercetools/sdk-middleware-auth`,`@commercetools/sdk-middleware-http`, `@commercetools/typescript-sdk`, and `dotenv` are already installed as part of [Getting started with TypeScript SDK and GraphQL](#getting-started) tutorial. Back at the command line, run the program using the following command: -``` -$ node whereClauseQuery.js -where clause query with GraphQL and TypeScript SDK -``` -If you see the same output as above, we’re ready to start. - -### Create an API client -You already have API client from the [Getting started with TypeScript SDK and GraphQL](#getting-started) tutorial on `project.js` file. -Re-open `whereClauseQuery.js` and add the following code: -```js -const { - ADMIN_CLIENT_ID, - ADMIN_CLIENT_SECRET, -} = process.env; - -const projectKey = '' - -// Create a httpMiddleware for the your project AUTH URL -const authMiddleware = createAuthMiddlewareForClientCredentialsFlow({ - host: '', + const { createAuthMiddlewareForClientCredentialsFlow } = require('@commercetools/sdk-middleware-auth') + const { createHttpMiddleware } = require('@commercetools/sdk-middleware-http') + const { createApiBuilderFromCtpClient } = require("@commercetools/typescript-sdk") + const fetch = require('node-fetch') + require('dotenv').config() + //reference API client credentials from environment variables + const { + CTP_PROJECT_KEY, + CTP_CLIENT_SECRET, + CTP_CLIENT_ID, + CTP_AUTH_URL, + CTP_API_URL, + CTP_SCOPES, + } = process.env + const projectKey = CTP_PROJECT_KEY + const authMiddleware = createAuthMiddlewareForClientCredentialsFlow({ + host: CTP_AUTH_URL, projectKey, credentials: { - clientId: ADMIN_CLIENT_ID, - clientSecret: ADMIN_CLIENT_SECRET, + clientId: CTP_CLIENT_ID, + clientSecret: CTP_CLIENT_SECRET, }, - scopes: [''], - fetch, -}) - -// Create a httpMiddleware for the your project API URL -const httpMiddleware = createHttpMiddleware({ - host: '', + scopes: [CTP_SCOPES], fetch, + }) + const httpMiddleware = createHttpMiddleware({ + host: CTP_API_URL, fetch, -}) - -// Create a client using authMiddleware and httpMiddleware -const client = createClient({ + }) + const client = createClient({ middlewares: [authMiddleware, httpMiddleware], -}) - -// Create a API root from API builder of commercetools platform client -const apiRoot = createApiBuilderFromCtpClient(client) + }) + // Create an API root from API builder of commercetools platform client + const apiRoot = createApiBuilderFromCtpClient(client); + console.log('where clause query with GraphQL and TypeScript SDK'); +``` +Environment variables and Nodejs dependencies `@commercetools/sdk-client`, `@commercetools/sdk-middleware-auth`,`@commercetools/sdk-middleware-http`, `@commercetools/typescript-sdk`, and `dotenv` are already installed as part of [Getting started with TypeScript SDK and GraphQL](#getting-started) tutorial. Back at the command line, run the program using the following command: +``` +$ node whereClauseQuery.js +where clause query with GraphQL and TypeScript SDK ``` -Replace the value ``, ``, `` and `` with your client `projectKey`, `host API_URL`, `scopes`, and `host Auth_URL` values from `project.js` file. +If you see the same output as above, we’re ready to start. ### Create GraphQL query and mutation Add the following code to `whereClauseQuery.js`. From f498e6b2880857dcc8c2c2fc3c044d8a40c6a72a Mon Sep 17 00:00:00 2001 From: Anil Kumar Date: Mon, 7 Jun 2021 22:38:01 +0200 Subject: [PATCH 7/9] Update whereclause --- docs/sdk/api/graphQLTypescriptSdk.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/sdk/api/graphQLTypescriptSdk.md b/docs/sdk/api/graphQLTypescriptSdk.md index b556d13d1..551b4be30 100644 --- a/docs/sdk/api/graphQLTypescriptSdk.md +++ b/docs/sdk/api/graphQLTypescriptSdk.md @@ -356,18 +356,20 @@ const whereClauseCustomerIdVariable = { const getCustomerByWhereClauseQuery = ` query ($where: String) { customers (where: $where) { - email - firstName + results { + email + firstName + } } } `; ``` -`whereClauseCustomerIdVariable` contains where clause with value `"id=\"\""`. For details about `where` query refer [Query Predicates](https://docs.commercetools.com/api/predicates/query) documentation. Replace `` with your customer [id](https://docs.commercetools.com/api/general-concepts#identifier) for which you would like to retrieve customer `email` and `firstName`. +`whereClauseCustomerIdVariable` contains where clause with value `"id=\"\""`. For details about `where` query, refer [Query Predicates](https://docs.commercetools.com/api/predicates/query) documentation. Replace `` with your customer [id](https://docs.commercetools.com/api/general-concepts#identifier) for which you would like to retrieve customer `email` and `firstName`. `getCustomerByWhereClauseQuery` is the GraphQL **query** to get customer info `email` and `firstName` by using **where clause** and **customer id** query predicate. -To explore commercetools GraphQL API you can use an interactive [GraphiQL environment](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) which is available as a part of [ImpEx & API Playground](https://docs.commercetools.com/docs/login). +To explore commercetools GraphQL API, you can use an interactive [GraphiQL environment](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) available as a part of [ImpEx & API Playground](https://docs.commercetools.com/docs/login). ### Call API to get customer information using TypeScript SDK and GraphQL @@ -380,7 +382,7 @@ const getCustomerByWhereClause = async () => apiRoot.withProjectKey({projectKey} variables: whereClauseCustomerIdVariable } }) - .execute() + .execute(); (async () => { try { @@ -389,7 +391,7 @@ const getCustomerByWhereClause = async () => apiRoot.withProjectKey({projectKey} } catch (error) { console.log('ERROR --->', error) } -})() +})(); ``` Run the program. The output should look like the following if the request is successful: From 129add4aa87d65c9c8e01336c3d85c79451eefd0 Mon Sep 17 00:00:00 2001 From: Anil Kumar Date: Thu, 10 Jun 2021 08:01:39 +0200 Subject: [PATCH 8/9] Update GraphQL console link --- docs/sdk/api/graphQLTypescriptSdk.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/sdk/api/graphQLTypescriptSdk.md b/docs/sdk/api/graphQLTypescriptSdk.md index 551b4be30..aa73d9077 100644 --- a/docs/sdk/api/graphQLTypescriptSdk.md +++ b/docs/sdk/api/graphQLTypescriptSdk.md @@ -109,7 +109,7 @@ const projectSettingsQuery = ` } })(); ``` -Then the client will **execute** get project information request from `apiRoot` using **TypeScript SDK** and **GraphQL** query[projectSettingsQuery] to get project settings. `projectSettingsQuery` retrieves project's `name`, `languages`,`currencies`,`countries`, `version` and `createdAt` fields. To explore commercetools GraphQL API, you can use an interactive [GraphiQL environment](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) available as a part of our [ImpEx & API Playground](https://docs.commercetools.com/docs/login). +Then the client will **execute** get project information request from `apiRoot` using **TypeScript SDK** and **GraphQL** query[projectSettingsQuery] to get project settings. `projectSettingsQuery` retrieves project's `name`, `languages`,`currencies`,`countries`, `version` and `createdAt` fields. To explore commercetools GraphQL API, you can use an interactive [GraphQL console](https://docs.commercetools.com/api/graphql#interactive-graphql-console). Run the program. The output should look like the following if the request is successful: @@ -231,7 +231,7 @@ const getCustomerByIdQuery = ` `getCustomerByIdQuery` is the GraphQL **query** to get newly created customer info `email` and `firstName` by `id`. -To explore commercetools GraphQL API you can use an interactive [GraphiQL environment](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) which is available as a part of [ImpEx & API Playground](https://docs.commercetools.com/docs/login). +To explore commercetools GraphQL API you can use an interactive [GraphQL console](https://docs.commercetools.com/api/graphql#interactive-graphql-console). ### Call API to create new Customer using TypeScript SDK and GraphQL API @@ -347,9 +347,9 @@ If you see the same output as above, we’re ready to start. Add the following code to `whereClauseQuery.js`. ```js -// where clause with query by customer id +// where clause with query by email const whereClauseCustomerIdVariable = { - "where": "id=\"\"" + "where": "email=\"your.test-1@test.com\"" }; // GraphQL query to get customer `email` and `firstName` using where clause and customer id query predicate @@ -369,7 +369,7 @@ const getCustomerByWhereClauseQuery = ` `getCustomerByWhereClauseQuery` is the GraphQL **query** to get customer info `email` and `firstName` by using **where clause** and **customer id** query predicate. -To explore commercetools GraphQL API, you can use an interactive [GraphiQL environment](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) available as a part of [ImpEx & API Playground](https://docs.commercetools.com/docs/login). +To explore commercetools GraphQL API, you can use an interactive [GraphQL console](https://docs.commercetools.com/api/graphql#interactive-graphql-console). ### Call API to get customer information using TypeScript SDK and GraphQL From 3bd99bdd3bbc0c5881c83bffc50bac961491b078 Mon Sep 17 00:00:00 2001 From: Stefan Meissner Date: Thu, 8 Jul 2021 09:46:02 +0200 Subject: [PATCH 9/9] Stringifies JSON for better readable log output. --- docs/sdk/api/graphQLTypescriptSdk.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/sdk/api/graphQLTypescriptSdk.md b/docs/sdk/api/graphQLTypescriptSdk.md index aa73d9077..20316d7b6 100644 --- a/docs/sdk/api/graphQLTypescriptSdk.md +++ b/docs/sdk/api/graphQLTypescriptSdk.md @@ -99,7 +99,7 @@ const projectSettingsQuery = ` }) .execute() .then(data => { - console.log('Project information --->', data); + console.log('Project information --->', JSON.stringify(data)); }) .catch(error => { console.log('ERROR --->', error);