0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Google SpreadSheetのデータをHTTP(GAS)で抜いて、AWS S3へ格納するlamdba処理(メモ)

Last updated at Posted at 2021-05-26

目的

GASにHTTPアクセスすると、必ず1度リダイレクトされるため、HTTPアクセス元のシステムによってはデータを取得できない。
(iOS Podcastでは、Google SpreadSheetとGASで用意した自前のRSSを食ってくれない)

lamdbaでGASを叩き、テキストファイルをS3へ格納する(実装方法は趣味です)

lamdbaコード

index.js

const gas_url = "GAS_URL";         //要編集
const backet = "S3_backet_name";   //要編集
const file = "file_name";          //要編集


const AWS = require('aws-sdk');
const https = require('https');

// リダイレクト先 URL を取得する関数
function get_redirect_url(src_url) {
  console.log("Call get_redirect_url");
  return new Promise((resolve, reject) => {
    try {
      // 4xx や 5xx ではエラーが発生しないので注意
      https.get(src_url, (res) => {
        // HTTP レスポンスから Location ヘッダを取得 (ヘッダ名は小文字)
        resolve(res.headers['location'])
      }).on('error', (err) => {
        reject(err)
      })
    } catch(err) {
      reject(err)
    }
  })
}

function get_text_write_s3(url){
  console.log("Call get_text_write_s3");
  return new Promise((resolve, reject) => {
    try {
      let str = '';
      https.get(url, (resp) => {
    
        resp.on('data', (chunk) => { 
          str += chunk; 
        }).on('end', () => { 
          
          //write to S3
          if(str.length > 920){// header+footer size ≒ 920
            // Load the AWS SDK for Node.js
            AWS.config.update({region: 'us-east-2'});
            // Create S3 service object
            s3 = new AWS.S3({apiVersion: '2006-03-01'});

            // call S3 to retrieve upload file to specified bucket
            const uploadParams = {Bucket: backet, Key: file, Body: str};
            
            // call S3 to retrieve upload file to specified bucket
            s3.upload (uploadParams, function (err, data) {
              if (err) {
                console.log("Error", err);
              } if (data) {
                console.log("Upload Success", data.Location);
              }
            });
            
            
          }
        });
      }).on('error', (err) => {
        reject(err)
      })

    } catch(err) {
      reject(err)
    }
  })
  
}


exports.handler = async (event, context) => {
  // リダイレクト先URLを取得
  const redirect_url = await get_redirect_url(gas_url)
    .catch(err => {
      console.log(err)
    })
  
  // リダイレクト先URLでデータ取得し、S3へ書き込み
  if (redirect_url) {
    await get_text_write_s3(redirect_url);
    context.succeed("OK");
  }
};

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?