Google Sheets + JS 클래스 = DX 프로토타이핑의 꿈

개발자 경험은 우리 팀#HAXTheWeb이 매우 중요하게 생각하는 것입니다. 문서를 개선하기 위해 항상 노력하는 동안(그리고 그들은 그것을 필요로 합니다!) 우리는 지역 개발 경험을 다음 단계로 끌어올릴 수 있는 유틸리티와 주석에 집중하는 것을 좋아합니다. 최근 우연히 발견한 한 가지 접근 방식은 애플리케이션 프로토타이핑을 위한 "API 백엔드"로 Google 스프레드시트를 사용한다는 아이디어였습니다.

코드를 해싱할 수 있습니다.



이것은 npm에 대한 우리 코드베이스의 다음 릴리스에서 게시될 예정이지만 지금은 액세스할 수 있습니다in our mono repo directly.

다음은 참조용 코드 인라인입니다.

import { CSVtoArray } from "@lrnwebcomponents/utils/utils.js";

export class gSheetInterface {
  constructor(target = null, sheetGids = {}) {
    // machineName you want to use => gid from google
    this.sheetGids = sheetGids;
    // sheet
    this.sheet = null;
    this.target = target;
  }
  /**
   * load data from sheet via API
   */
  async loadSheetData(page) {
    return await this.loadCSVData(
      `https://docs.google.com/spreadsheets/d/e/${this.sheet}/pub?output=csv&gid=${this.sheetGids[page]}`,
      page
    );
  }
  /**
   * generate appstore query
   */
  async loadCSVData(source, sheet) {
    return await fetch(source, {
      method: this.method,
    })
      .then((response) => {
        if (response.ok) return response.text();
      })
      .then((text) => {
        return this.handleResponse(text, sheet);
      });
  }
  /**
   * Convert from csv text to an array in the table function
   */
  async handleResponse(text, sheet) {
    // Set helps performantly assemble possible collapsed areas
    let table = CSVtoArray(text);
    let tmp = table.shift();
    let headings = {};
    let data = [];
    for (var i in tmp) {
      headings[tmp[i]] = i;
    }
    for (var i in table) {
      let item = {};
      for (var j in headings) {
        item[j] = table[i][headings[j]];
      }
      // push data onto the database of all data we have now as objects
      data.push(item);
    }
    // allow for deeper processing on the data or just return the data found
    return typeof this.target[`process${sheet}Data`] === "function"
      ? this.target[`process${sheet}Data`](table, headings, data)
      : data;
  }
}



코드에서 이것을 사용하는 단계


  • 시트를 만든 다음 시트를 게시합니다.

  • 생성하는 이 주소의 KEYNAMEHERE 부분을 가져옵니다. https://docs.google.com/spreadsheets/d/e/[KEYNAMEHERE]/pubhtml
  • 이것은 this.sheet
  • 입니다.
  • 그런 다음 구조{yourNameYouWant: 0}의 개체를 호출합니다.
  • 이것은 Google 시트에서 생성하는 각 추가 페이지의 URL에 gid를 형성합니다.

  • 웹 구성 요소에 대한 통합 상용구 예제




    import { gSheetInterface } from "@lrnwebcomponents/utils/lib/gSheetInterface.js";
    export class MyElement extends HTMLElement {
      constructor() {
        super();
        // whatever variable you want for your storage internally
        this.database = {};
        // instance of the class to interface with, add more
        // page gid's to the object with nameYouWant being a key
        // so that you can reference it after the fact
        this.gSI = new gSheetInterface(this, { nameYouWant: 0 });
        this.gSI.sheet = "what-ever-your-shee-id-is-after-publish"; /* replace with your sheetID here */
      }
    
      async connectedCallback() {
        // loop through all the sheet GIDs and load the data
        for (var i in this.gSheet.sheetGids) {
          this.database[i] = await this.gSheet.loadSheetData(i);
        }
        // render the data however you want now that the
        // "database" has been populated with values
      }
      static get tag() {
        return "my-element";
      }
    }
    customElements.define(MyElement.tag, MyElement);
    


    구현된 사용 사례 보기



    이것은 grade-book element we're currently working on에서 사용되는 것을 볼 수 있습니다. 이렇게 하면 gSheetInterface 클래스의 인스턴스가 생성된 다음 이를 활용하여 채점 인터페이스를 채웁니다(아직 많이 개발 중이지만 기능적임).

    로드 시퀀스의 짧은 비디오



    다음은 약 한 달 전 grade-book의 짧은 비디오(소리 없음)입니다.


    전체 Google Docs API 설정 대신 이것을 사용하는 이유


  • 여기에는 API 설정이 필요하지 않으며 주니어 개발자(및 비개발자)는 Google 시트를 게시하여 API를 설정할 수 있습니다
  • .
  • 시트 내의 페이지(gid's)가 일관되게 유지되어 시트를 다른 위치로 복제하여 다른 "앱"을 연결할 때 DX를 개선합니다
  • .
  • 원시 JSON blob 편집이 아닌 동안 빠르게 개발/혼란을 일으키는 속도

  • 이 대 전체 API 액세스의 제한 사항


  • 읽기 전용. 답장할 수 없음
  • 속도 제한이 있는지 확실하지 않음(아직 접해보지 않음)
  • 모든 데이터를 가져오므로 막대한 시트/페이지가 순차적으로 매우 느리게 로드됩니다(잠재적으로)
  • .
  • 업데이트 속도까지 알 수 없는 캐싱 정책

  • 이것이 누군가에게 유용했기를 바랍니다. 누구나 쉽게 "데이터베이스"로 이동하여 업데이트할 수 있는 무언가와 인터페이스하는 매우 멋진 방법입니다. 저는 데이터에 접근하고 조작하는 진입 방법에 대한 이런 종류의 낮은 장벽이 마음에 듭니다. 성적표 앱의 UX가 더욱 정교해짐에 따라 향후 동영상과 게시물을 제공할 수 있기를 바랍니다.

    좋은 웹페이지 즐겨찾기