Skip to content

Commit 289bafc

Browse files
authored
Merge pull request #2975 from GoogleCloudPlatform/nodejs-retail-migration
migrate code from googleapis/nodejs-retail
2 parents 208182f + 56d04e6 commit 289bafc

File tree

76 files changed

+5995
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

76 files changed

+5995
-0
lines changed

.github/auto-label.yaml

+1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ path:
3333
mediatranslation: "mediatranslation"
3434
memorystore: "memorystore"
3535
monitoring: "monitoring"
36+
retail: "retail"
3637
run: "run"
3738
scheduler: "cloudscheduler"
3839
secret-manager: "secretmanager"

.github/workflows/generate.js

100644100755
File mode changed.

.github/workflows/retail.yaml

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
name: retail
2+
on:
3+
push:
4+
branches:
5+
- main
6+
paths:
7+
- 'retail/**'
8+
- '.github/workflows/retail.yaml'
9+
pull_request:
10+
paths:
11+
- 'retail/**'
12+
- '.github/workflows/retail.yaml'
13+
pull_request_target:
14+
types: [labeled]
15+
paths:
16+
- 'retail/**'
17+
- '.github/workflows/retail.yaml'
18+
schedule:
19+
- cron: '0 0 * * 0'
20+
jobs:
21+
test:
22+
if: ${{ github.event.action != 'labeled' || github.event.label.name == 'actions:force-run' }}
23+
runs-on: ubuntu-latest
24+
timeout-minutes: 60
25+
permissions:
26+
contents: 'write'
27+
pull-requests: 'write'
28+
id-token: 'write'
29+
steps:
30+
- uses: actions/[email protected]
31+
with:
32+
ref: ${{github.event.pull_request.head.sha}}
33+
- uses: 'google-github-actions/[email protected]'
34+
with:
35+
workload_identity_provider: 'projects/1046198160504/locations/global/workloadIdentityPools/github-actions-pool/providers/github-actions-provider'
36+
service_account: '[email protected]'
37+
create_credentials_file: 'true'
38+
access_token_lifetime: 600s
39+
- uses: actions/[email protected]
40+
with:
41+
node-version: 16
42+
- run: npm install
43+
working-directory: retail
44+
- run: npm test
45+
working-directory: retail
46+
env:
47+
MOCHA_REPORTER_SUITENAME: retail
48+
MOCHA_REPORTER_OUTPUT: retail_sponge_log.xml
49+
MOCHA_REPORTER: xunit
50+
- if: ${{ github.event.action == 'labeled' && github.event.label.name == 'actions:force-run' }}
51+
uses: actions/github-script@v6
52+
with:
53+
github-token: ${{ secrets.GITHUB_TOKEN }}
54+
script: |
55+
try {
56+
await github.rest.issues.removeLabel({
57+
name: 'actions:force-run',
58+
owner: 'GoogleCloudPlatform',
59+
repo: 'nodejs-docs-samples',
60+
issue_number: context.payload.pull_request.number
61+
});
62+
} catch (e) {
63+
if (!e.message.includes('Label does not exist')) {
64+
throw e;
65+
}
66+
}
67+
- if: ${{ github.event_name == 'schedule' && always() }}
68+
run: |
69+
curl https://github.com/googleapis/repo-automation-bots/releases/download/flakybot-1.1.0/flakybot -o flakybot -s -L
70+
chmod +x ./flakybot
71+
./flakybot --repo GoogleCloudPlatform/nodejs-docs-samples --commit_hash ${{github.sha}} --build_url https://github.com/${{github.repository}}/actions/runs/${{github.run_id}}

.github/workflows/workflows.json

+1
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373
"monitoring/opencensus",
7474
"monitoring/prometheus",
7575
"monitoring/snippets",
76+
"retail",
7677
"scheduler",
7778
"security-center/snippets",
7879
"service-directory/snippets",

CODEOWNERS

+3
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,6 @@ texttospeech @GoogleCloudPlatform/dee-data-ai @GoogleCloudPlatform/nodejs-sample
7373
translate @GoogleCloudPlatform/dee-data-ai @GoogleCloudPlatform/nodejs-samples-reviewers
7474
video-intelligence @GoogleCloudPlatform/dee-data-ai @GoogleCloudPlatform/nodejs-samples-reviewers
7575
vision @GoogleCloudPlatform/dee-data-ai @GoogleCloudPlatform/nodejs-samples-reviewers
76+
77+
# Self-service
78+
retail @GoogleCloudPlatform/cloud-retail-team @GoogleCloudPlatform/nodejs-samples-reviewers

retail/.mocharc.json

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"timeout": "600000",
3+
"recursive": true,
4+
"spec": ["test/*.js", "interactive-tutorials/test/*.js"]
5+
}
+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
2+
## Get started with Google Cloud Retail
3+
4+
### Select your project and enable the Retail API
5+
6+
Google Cloud organizes resources into projects. This lets you
7+
collect all the related resources for a single application in one place.
8+
9+
If you don't have a Google Cloud project yet or you're not the Owner of an existing one, you can
10+
[create a new project](https://console.cloud.google.com/projectcreate).
11+
12+
After the project is created, set your PROJECT_ID to a ```project``` variable.
13+
1. Run the following command in Terminal:
14+
```bash
15+
gcloud config set project <YOUR_PROJECT_ID>
16+
```
17+
18+
1. Check that the Retail API is enabled for your Project in the [Admin Console](https://console.cloud.google.com/ai/retail/).
19+
20+
### Set up authentication
21+
22+
To run a code sample from the Cloud Shell, you need to authenticate. To do this, use the Application Default Credentials.
23+
24+
1. Set your user credentials to authenticate your requests to the Retail API
25+
26+
```bash
27+
gcloud auth application-default login
28+
```
29+
30+
1. Type `Y` and press **Enter**. Click the link in Terminal. A browser window should appear asking you to log in using your Google account.
31+
32+
1. Provide the Google Auth Library with access to your credentials and paste the code from the browser to the Terminal.
33+
34+
1. Run the code sample and check the Retail API in action.
35+
36+
**Note**: Click the copy button on the side of the code box to paste the command in the Cloud Shell terminal and run it.
37+
38+
### Set the GCLOUD_PROJECT environment variable
39+
40+
Because you are going to run the code samples in your own Google Cloud project, you should specify the **project_number** as an environment variable. It will be used in every request to the Retail API.
41+
42+
1. You can find the ```project_number``` in the **Home/Dashboard/Project Info card**.
43+
44+
1. Set the environment variable with the following command:
45+
```bash
46+
export GCLOUD_PROJECT=<YOUR_GCLOUD_PROJECT>
47+
```
48+
49+
### Install Google Cloud Retail libraries
50+
51+
To install all the dependencies, run
52+
53+
```
54+
cd cloudshell_open/nodejs-retail
55+
npm install
56+
```
57+
58+
### Running the code samples
59+
Samples are in the `search/`, `products/`, `events/` directories.
60+
To execute an individual code sample, invoke `node` with a file as a parameter at the command line prompt, e.g.:
61+
62+
```
63+
node search/search-simple-query.js
64+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// Copyright 2022 Google Inc. All Rights Reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
async function main(datasetId) {
18+
// Imports the Google Cloud client library.
19+
const {UserEventServiceClient} = require('@google-cloud/retail').v2;
20+
21+
// Instantiates a client.
22+
const retailClient = new UserEventServiceClient();
23+
24+
const projectId = await retailClient.getProjectId();
25+
const dataSchema = 'user_event';
26+
const tableId = 'events'; // TO CHECK ERROR HANDLING USE THE TABLE OF INVALID USER EVENTS
27+
28+
// Placement
29+
const parent = `projects/${projectId}/locations/global/catalogs/default_catalog`; // TO CHECK ERROR HANDLING PASTE THE INVALID CATALOG NAME HERE
30+
31+
// The desired input location of the data.
32+
const inputConfig = {
33+
bigQuerySource: {
34+
projectId,
35+
datasetId,
36+
tableId,
37+
dataSchema,
38+
},
39+
};
40+
41+
const IResponseParams = {
42+
IImportUserEventsResponse: 0,
43+
IImportMetadata: 1,
44+
IOperation: 2,
45+
};
46+
47+
const callImportUserEvents = async () => {
48+
// Construct request
49+
const request = {
50+
parent,
51+
inputConfig,
52+
};
53+
54+
console.log('Import request: ', request);
55+
56+
// Run request
57+
const [operation] = await retailClient.importUserEvents(request);
58+
const response = await operation.promise();
59+
const result = response[IResponseParams.IImportMetadata];
60+
console.log(
61+
`Number of successfully imported events: ${result.successCount | 0}`
62+
);
63+
console.log(
64+
`Number of failures during the importing: ${result.failureCount | 0}`
65+
);
66+
console.log(`Operation result: ${JSON.stringify(response)}`);
67+
};
68+
69+
console.log('Start events import');
70+
await callImportUserEvents();
71+
console.log('Events import finished');
72+
}
73+
74+
process.on('unhandledRejection', err => {
75+
console.error(err.message);
76+
process.exitCode = 1;
77+
});
78+
79+
main(
80+
...(() => {
81+
const argv = process.argv.slice(2);
82+
return argv.length ? argv : ['user_events'];
83+
})()
84+
);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// Copyright 2022 Google Inc. All Rights Reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
async function main(bucketName) {
18+
// Imports the Google Cloud client library.
19+
const {UserEventServiceClient} = require('@google-cloud/retail').v2;
20+
21+
// Instantiates a client.
22+
const retailClient = new UserEventServiceClient();
23+
24+
const projectId = await retailClient.getProjectId();
25+
26+
//TODO(developer) set the environment variable value which will be used as the bucket name
27+
const gcsBucket = `gs://${bucketName}`;
28+
const gcsErrorsBucket = `gs://${bucketName}/error`;
29+
const gcsEventsObject = 'user_events.json'; // TO CHECK ERROR HANDLING USE THE JSON WITH INVALID USER EVENTS
30+
31+
// Placement
32+
const parent = `projects/${projectId}/locations/global/catalogs/default_catalog`; // TO CHECK ERROR HANDLING PASTE THE INVALID CATALOG NAME HERE
33+
34+
// The desired input location of the data.
35+
const inputConfig = {
36+
gcsSource: {
37+
inputUris: [gcsBucket + '/' + gcsEventsObject],
38+
dataSchema: 'user_event',
39+
},
40+
};
41+
42+
// The desired location of errors incurred during the Import.
43+
const errorsConfig = {
44+
gcsPrefix: gcsErrorsBucket,
45+
};
46+
47+
const IResponseParams = {
48+
IImportUserEventsResponse: 0,
49+
IImportMetadata: 1,
50+
IOperation: 2,
51+
};
52+
53+
const callImportUserEvents = async () => {
54+
// Construct request
55+
const request = {
56+
parent,
57+
inputConfig,
58+
errorsConfig,
59+
};
60+
61+
console.log('Import request: ', request);
62+
63+
// Run request
64+
const [operation] = await retailClient.importUserEvents(request);
65+
const response = await operation.promise();
66+
const result = response[IResponseParams.IImportMetadata];
67+
console.log(
68+
`Number of successfully imported events: ${result.successCount | 0}`
69+
);
70+
console.log(
71+
`Number of failures during the importing: ${result.failureCount | 0}`
72+
);
73+
console.log(`Operation result: ${JSON.stringify(response)}`);
74+
};
75+
76+
console.log('Start events import');
77+
await callImportUserEvents();
78+
console.log('Events import finished');
79+
}
80+
81+
process.on('unhandledRejection', err => {
82+
console.error(err.message);
83+
process.exitCode = 1;
84+
});
85+
86+
main(
87+
...(() => {
88+
const argv = process.argv.slice(2);
89+
return argv.length ? argv : [process.env['EVENTS_BUCKET_NAME']];
90+
})()
91+
);

0 commit comments

Comments
 (0)