การเริ่มต้นอย่างรวดเร็วด้วย Node.js

การเริ่มต้นอย่างรวดเร็วอธิบายวิธีตั้งค่าและเรียกใช้แอปที่เรียกใช้ Google Workspace API

การเริ่มต้นใช้งาน Google Workspace อย่างรวดเร็วจะใช้ไลบรารีของไคลเอ็นต์ API เพื่อจัดการรายละเอียดบางอย่างของขั้นตอนการตรวจสอบสิทธิ์และการให้สิทธิ์ เราขอแนะนำให้คุณใช้ไลบรารีของไคลเอ็นต์สำหรับแอปของคุณเอง การเริ่มต้นอย่างรวดเร็วนี้ใช้วิธีการการตรวจสอบสิทธิ์ที่เรียบง่ายซึ่งเหมาะสำหรับสภาพแวดล้อมการทดสอบ สำหรับสภาพแวดล้อมเวอร์ชันที่ใช้งานจริง เราขอแนะนำให้เรียนรู้เกี่ยวกับการตรวจสอบสิทธิ์และการให้สิทธิ์ก่อนเลือกข้อมูลเข้าสู่ระบบที่เหมาะกับแอปของคุณ

สร้างแอปพลิเคชันบรรทัดคำสั่ง Node.js ที่ส่งคำขอไปยัง Drive Labels API

วัตถุประสงค์

  • ตั้งค่าสภาพแวดล้อมของคุณ
  • ติดตั้งไลบรารีของไคลเอ็นต์
  • ตั้งค่าตัวอย่าง
  • เรียกใช้ตัวอย่าง

ข้อกำหนดเบื้องต้น

  • บัญชี Google

ตั้งค่าสภาพแวดล้อมของคุณ

ตั้งค่าสภาพแวดล้อมเพื่อให้การเริ่มต้นอย่างรวดเร็วนี้เสร็จสมบูรณ์

เปิดใช้ API

ก่อนใช้ Google APIs คุณต้องเปิดใช้ API ในโปรเจ็กต์ Google Cloud คุณเปิด API ได้มากกว่า 1 รายการในโปรเจ็กต์ Google Cloud เดียว

ให้สิทธิ์ข้อมูลเข้าสู่ระบบสำหรับแอปพลิเคชันเดสก์ท็อป

หากต้องการตรวจสอบสิทธิ์ผู้ใช้ปลายทางและเข้าถึงข้อมูลผู้ใช้ในแอป คุณต้องสร้างรหัสไคลเอ็นต์ OAuth 2.0 อย่างน้อย 1 รายการ รหัสไคลเอ็นต์ใช้เพื่อระบุแอปเดียวไปยังเซิร์ฟเวอร์ OAuth ของ Google หากแอปทำงานในหลายแพลตฟอร์ม คุณต้องสร้างรหัสไคลเอ็นต์แยกกันสำหรับแต่ละแพลตฟอร์ม
  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > API และบริการ > ข้อมูลเข้าสู่ระบบ

    ไปที่ข้อมูลเข้าสู่ระบบ

  2. คลิกสร้างข้อมูลเข้าสู่ระบบ > รหัสไคลเอ็นต์ OAuth
  3. คลิกประเภทแอปพลิเคชัน > แอปบนเดสก์ท็อป
  4. ในช่องชื่อ ให้พิมพ์ชื่อของข้อมูลเข้าสู่ระบบ ชื่อนี้จะแสดงในคอนโซล Google Cloud เท่านั้น
  5. คลิกสร้าง หน้าจอที่สร้างของไคลเอ็นต์ OAuth จะปรากฏขึ้นเพื่อแสดงรหัสไคลเอ็นต์และรหัสลับไคลเอ็นต์ใหม่
  6. คลิกตกลง ข้อมูลเข้าสู่ระบบที่สร้างขึ้นใหม่จะปรากฏในส่วนรหัสไคลเอ็นต์ OAuth 2.0
  7. บันทึกไฟล์ JSON ที่ดาวน์โหลดเป็น credentials.json และย้ายไฟล์ไปยังไดเรกทอรีการทำงาน

ติดตั้งไลบรารีของไคลเอ็นต์

  • ติดตั้งไลบรารีโดยใช้ npm:

    npm install googleapis@113 @google-cloud/local-auth@2.1.1 --save
    

ตั้งค่าตัวอย่าง

  1. สร้างไฟล์ชื่อ index.js ในไดเรกทอรีการทำงาน

  2. วางรหัสต่อไปนี้ในไฟล์

        const fs = require('fs');
        const readline = require('readline');
        const {google} = require('googleapis');
    
        // If modifying these scopes, delete token.json.
        const SCOPES = ['https://www.googleapis.com/auth/drive.labels.readonly'];
        // The file token.json stores the user's access and refresh tokens, and is
        // created automatically when the authorization flow completes for the first
        // time.
        const TOKEN_PATH = 'token.json';
    
        // Load client secrets from a local file.
        fs.readFile('credentials.json', (err, content) => {
          if (err) return console.log('Error loading client secret file:', err);
          // Authorize a client with credentials, then call the Google Drive Labels
          // API.
          authorize(JSON.parse(content), listDriveLabels);
        });
    
        /**
        * Create an OAuth2 client with the given credentials, and then execute the
        * given callback function.
        * @param {Object} credentials The authorization client credentials.
        * @param {function} callback The callback to call with the authorized client.
        */
        function authorize(credentials, callback) {
          const {client_secret, client_id, redirect_uris} = credentials.installed;
          const oAuth2Client = new google.auth.OAuth2(
              client_id, client_secret, redirect_uris[0]);
    
          // Check if we have previously stored a token.
          fs.readFile(TOKEN_PATH, (err, token) => {
            if (err) return getNewToken(oAuth2Client, callback);
            oAuth2Client.setCredentials(JSON.parse(token));
            callback(oAuth2Client);
          });
        }
    
        /**
        * Get and store new token after prompting for user authorization, and then
        * execute the given callback with the authorized OAuth2 client.
        * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
        * @param {getEventsCallback} callback The callback for the authorized client.
        */
        function getNewToken(oAuth2Client, callback) {
          const authUrl = oAuth2Client.generateAuthUrl({
            access_type: 'offline',
            scope: SCOPES,
          });
          console.log('Authorize this app by visiting this url:', authUrl);
          const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout,
          });
          rl.question('Enter the code from that page here: ', (code) => {
            rl.close();
            oAuth2Client.getToken(code, (err, token) => {
              if (err) return console.error('Error retrieving access token', err);
              oAuth2Client.setCredentials(token);
              // Store the token to disk for later program executions
              fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                if (err) return console.error(err);
                console.log('Token stored to', TOKEN_PATH);
              });
              callback(oAuth2Client);
            });
          });
        }
    
        function listDriveLabels(auth) {
          const service = google.drivelabels({version: 'v2', auth});
          const params = {
            'view': 'LABEL_VIEW_FULL'
          };
          service.labels.list(params, (err, res) => {
            if (err) return console.error('The API returned an error: ' + err);
            const labels = res.data.labels;
            if (labels) {
              labels.forEach((label) => {
                const name = label.name;
                const title = label.properties.title;
                console.log(`${name}\t${title}`);
              });
            } else {
              console.log('No Labels');
            }
          });
        }
    

เรียกใช้ตัวอย่าง

  1. เรียกใช้ตัวอย่างในไดเรกทอรีการทำงาน

    node .
    
  2. ครั้งแรกที่คุณเรียกใช้ตัวอย่าง ระบบจะแสดงข้อความแจ้งให้คุณให้สิทธิ์เข้าถึง ดังนี้

    1. หากคุณยังไม่ได้ลงชื่อเข้าใช้บัญชี Google ของคุณ ระบบจะแจ้งให้คุณลงชื่อเข้าใช้ หากคุณลงชื่อเข้าใช้หลายบัญชี ให้เลือก 1 บัญชีที่จะใช้สำหรับการให้สิทธิ์
    2. คลิกยอมรับ

    ข้อมูลการให้สิทธิ์จะจัดเก็บไว้ในระบบไฟล์ ดังนั้นเมื่อคุณเรียกใช้โค้ดตัวอย่างในครั้งถัดไป คุณจะไม่ได้รับข้อความแจ้งให้ให้สิทธิ์

คุณสร้างแอปพลิเคชัน Nodejs แรกที่ส่งคำขอไปยัง Drive Labels API สำเร็จแล้ว

ขั้นตอนถัดไป