google-sheet-db

npm version

For now, this is just some wrapper around Google Sheet for fetching and writing back data.

This is for use on Node.js server.

icon

Setup

Install the Package

Install the package via npm:

npm install @dobuki/google-sheet-db

Configure Environment Variables

Make sure to specify the SHEETS_SERVICE_KEY_FILE environment variable in your shell profile (e.g., .bashrc, .zshrc, or equivalent) to point to your service account credentials file.

export SHEETS_SERVICE_KEY_FILE="/path/to/sheets-service.json"

Replace /path/to/sheets-service.json with the actual path where you store your credentials file. After editing your profile, run source ~/.bashrc (or equivalent) to apply the changes, or restart your terminal. Alternatively, for local development, you can create a .env file in your project root:

SHEETS_SERVICE_KEY_FILE=/path/to/sheets-service.json
SPREADSHEET_ID=your-spreadsheet-id

Then, ensure your code loads it with dotenv (if not already included in the package):

npm install dotenv
require('dotenv').config();

Get sheets-service.json from Google Cloud API

Create a Google Cloud Project:

Generate the JSON Key:

Secure the File:

sheets-service.json
.env

For Updates, Grant Access to the Sheet

To allow the package to update your Google Sheet (not just read it):

Find the Service Account Email:

Share the Spreadsheet:

Verify Scope:

The package uses the https://www.googleapis.com/auth/spreadsheets scope by default, which supports both reading and writing. No additional scope changes are needed unless customized.

Usage

Fetch Data

const { listSheetsAndFetchData } = require('@dobuki/google-sheet-db');

async function fetchData() {
  const spreadsheetId = process.env.SPREADSHEET_ID || 'your-spreadsheet-id';
  const data = await listSheetsAndFetchData(spreadsheetId);
  console.log(data);
}

fetchData();

Returns an object mapping sheet titles to arrays of Row objects with typed values and formula info.

Update Data

const { listSheetsAndFetchData } = require('@dobuki/google-sheet-db');

async function updateData() {
  const spreadsheetId = process.env.SPREADSHEET_ID || 'your-spreadsheet-id';
  const data = await listSheetsAndFetchData(spreadsheetId);
  
  if (data && data['Sheet1']) {
    const row = data['Sheet1'][0];
    row['UpdatedField'] = 'Updated'; // Modify value
    
    const result = await updateSheetRow(spreadsheetId, rows);
    return result;
  }
}

updateData();

Github Source https://github.com/jacklehamster/google-sheet-db