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

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

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

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

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

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

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

  • บัญชี Google

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

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

เปิดใช้ API

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

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

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

    ไปที่ลูกค้า

  2. คลิกสร้างไคลเอ็นต์
  3. คลิกประเภทแอปพลิเคชัน > แอปเดสก์ท็อป
  4. พิมพ์ชื่อของข้อมูลเข้าสู่ระบบในช่องชื่อ ชื่อนี้จะแสดงในคอนโซล Google Cloud เท่านั้น
  5. คลิกสร้าง

    ข้อมูลเข้าสู่ระบบที่สร้างขึ้นใหม่จะปรากฏในส่วน "รหัสไคลเอ็นต์ OAuth 2.0"

  6. บันทึกไฟล์ 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 ระบบจะแจ้งให้ลงชื่อเข้าใช้ หากคุณลงชื่อเข้าใช้หลายบัญชี ให้เลือกบัญชีเดียวที่จะใช้สำหรับการให้สิทธิ์
    2. คลิกยอมรับ

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

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

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