Code Monkey home page Code Monkey logo

ng-google-sheets-db-library's Introduction

ng-google-sheets-db logo

ng-google-sheets-db - Angular Google Sheets DB

Test, lint, build and deploy demo: app demo: StackBlitz Angular: v10 npm npm license: MIT

Use Google Sheets as your (read-only) backend for your Angular app!

Google Sheets Table

const attributesMapping = {
  id: "ID",
  name: "Name",
  email: "Email Address",
  contact: {
    _prefix: "Contact ",
    street: "Street",
    streetNumber: "Street Number",
    zip: "ZIP",
    city: "City",
  },
  skills: {
    _prefix: "Skill ",
    _listField: true,
  },
};
googleSheetsDbService
  .get(
    "1gSc_7WCmt-HuSLX01-Ev58VsiFuhbpYVo8krbPCvvqA",
    "Characters",
    attributesMapping
  )
  .subscribe((characters: object[]) => {
    // Use the characters here
  });

Installation

ng add ng-google-sheets-db

or

npm install ng-google-sheets-db

Usage

Google Sheets

  1. Create a Google Sheet:
    • The first row must be the header.
    • The following rows are your entries, one entry per row.
    • You may have an active column, with which you can enable or disable rows/entries.
    • A Google Sheets demo spreadsheet is available here.
  2. Share your sheet:
    • [File] → [Share] → On the bottom of the modal at "Get Link" click [Change to anyone with the link] to be "Viewer".
    • Get the Spreadsheet ID (i.e. 1gSc_7WCmt-HuSLX01-Ev58VsiFuhbpYVo8krbPCvvqA): It is part of the Google spreadsheet URL.
    • Get the Sheet Name: The name of the worksheet can be found at the bottom of your Google spreadsheet.
  3. Optional: It may be a good idea to enable 2-Step Verification for your Google account, if you have not done it yet 😉.

Google Cloud Platform (GCP)

A good overview guide is the Get started as a Workspace developer.

  1. Create a new project in the Google Cloud Console.
  2. Enable Google Sheets API: [APIs & Services] → [Enable APIs and Services] → Search for "Google Sheets API" → [ENABLE].
  3. Create an API key: [APIs & Services] → [Credentials] → [+ CREATE CREDENTIALS] → [API key] → [RESTRICT KEY] → In "Application restrictions" choose "HTTP referrers (web sites)" with "Website restrictions" and in "API restrictions" choose "Restrict key" and select "Google Sheets API" → [SAVE].
  4. Get the generated API key.

Angular

Add GoogleSheetsDbService to your app's module as a provider and Angular's HttpClientModule to the imports:

import { HttpClientModule } from '@angular/common/http';

import { API_KEY, GoogleSheetsDbService } from 'ng-google-sheets-db';

@NgModule({
  ...
  imports: [
    HttpClientModule,
    ...
  ],
  providers: [
    {
      provide: API_KEY,
      useValue: <YOUR_GOOGLE_SHEETS_API_KEY>,
    },
    GoogleSheetsDbService
  ],
  ...
})
export class AppModule { }

Import and inject into your component's constructor:

import { GoogleSheetsDbService } from 'ng-google-sheets-db';

@Component({
  ...
})
export class YourComponent implements OnInit {
  characters$: Observable<Character[]>;

  constructor(private googleSheetsDbService: GoogleSheetsDbService) { }

  ngOnInit(): void {
    this.characters$ = this.googleSheetsDbService.get<Character>('1gSc_7WCmt-HuSLX01-Ev58VsiFuhbpYVo8krbPCvvqA', "Characters", characterAttributesMapping);
  }

Attributes Mapping

The attributesMapping maps the Google spreadsheet columns to to your outcome object.

const attributesMapping = {
  id: "ID",
  name: "Name",
  email: "Email Address",
  contact: {
    _prefix: "Contact ",
    street: "Street",
    streetNumber: "Street Number",
    zip: "ZIP",
    city: "City",
  },
  skills: {
    _prefix: "Skill ",
    _listField: true,
  },
};

For example, the Google spreadsheet column Email Address is mapped to the outcome object attribute email.

Nested objects

contact is an example of a nested object. You may define a _prefix as a prefix for all columns of the nested object. Please note that the _prefix may need a trailing whitespace.

Lists

skills is an example of a list. You need to set _listField and a _prefix for all columns of the list. In this example, all columns starting with _Skill _ and an increasing number are part of the list, i.e. Skill 1, Skill 2, etc. Please note that the _prefix may need a trailing whitespace.

Methods

get(spreadsheetId: string, worksheetName: string, attributesMapping: object | string[]): Observable<T[]>

const allCharacters$: Observable<Character> =
  googleSheetsDbService.get<Character>(
    "1gSc_7WCmt-HuSLX01-Ev58VsiFuhbpYVo8krbPCvvqA",
    "Characters",
    attributesMapping
  );

Get all rows from the Google spreadsheet as an Observable of objects or a given type as type variable T.

getActive(spreadsheetId: string, worksheetName: string, attributesMapping: object | string[], isActiveColumnName: string = 'is_active', activeValues: string[] | string = null): Observable<T[]>

const activeCharacters$: Observable<Character> =
  googleSheetsDbService.getActive<Character>(
    "1gSc_7WCmt-HuSLX01-Ev58VsiFuhbpYVo8krbPCvvqA",
    "Characters",
    attributesMapping,
    "Active"
  );

Get "active" rows from the Google spreadsheet as an Observable of objects or a given type as type variable T. You may have an active column with name isActiveColumnName, with which you can enable or disable rows/entries. "Active" rows have the value true, 1 or yes. You may also define your own activeValues.

Demo Application

Want to see an example of how to use ng-google-sheets-db? Check out the demo application in projects/demo or on StackBlitz.

License

MIT

ng-google-sheets-db-library's People

Contributors

franzdiebold avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ng-google-sheets-db-library's Issues

How to create single compontent to watch single object from array of objects?

Hi, how to create single view (dynamic - get params from on of fields from object).
Your native code return array of objects, fields name becomes from column name its ok. One of my colum is "idwar" i want to catch this and on click on the list open only single view (one object = row from google sheets). I dont know exactly how to correctly explain.

APIs are deprecated when will be updated with new?

Hi there,

I am trying to use your library and it works fine but sometimes this API gives a 404
https://spreadsheets.google.com/feeds/list/{worsheetId}/1/public/values?alt=json

I was trying to figure out the reason and found that it seems deprecated now as per this doc
https://developers.google.com/sheets/api/v3/data

so is that really deprecated that's why it gives sometimes 404 and sometimes it's working and in the past few days those 404 really increased a lot.

or is there something else issue?

can you help me with this issue?

Thanks,
Mitesh

Error in angular 12

Error: node_modules/ng-google-sheets-db/lib/google-sheets-db.service.d.ts:9:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

Hello!

I am facing this problem using your library and would like please if you can help me out to solve it, cannot understand where it comes from

Thank you

Regards

Access to XMLHttpRequest at 'https://accounts.google.com/ServiceLogin?service=wise&passive=1209600&continue=https://spreadsheets.google.com/feeds/list/------/-------/public/values?alt%3Djson&followup=https://spreadsheets.google.com/feeds/list/------/------/public/values?alt%3Djson&ltmpl=sheets' (redirected from 'https://spreadsheets.google.com/feeds/list/-----/-----/public/values?alt=json') from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

[Not an issue] Number vs string types

Sorry Franz, but I don't know other way of contact you without opening this issue.
It's not an issue, rather a silly JavaScript/TypeScript doubt that I stumble on, for which I have a workaround but I would apreciate if you could spare some of our knowlegde with me.

I was declaring my sheet's data interface with some field columns with type other than string, like semana: number; .
I would never guess that, in Angular's TypeScript environment, my whole program would run flawlessy holding string values in the Article.semana number-typed property! But actually it does!
Further in my code, I'm using ExcelJS to export an archive and I realise that, after fetching the google sheet I need to archive.semana = parseInt(archive.semana) and voilá: article.semana passes to hold a number instead of a string.

So, could you help me with the following 2 questions?

  1. ng-google-sheets-db-library package will always return a sequence of characters, no matter the type we declare in the data interface?
  2. how can a object's property of type number can hold a string without an error being thrown during execution of the JavaScript/TypeScript code?
export interface Article {
  semana: number;
  data_informe: string;
  ID: string;
  excluir: string;
  autores: string;
  titulo: string;
  tecnologias: string;
  sumario_achados: string;
  aval_qual_metod: string;
  resumo: string;
  referencia_bibliografica: string;
  país: string;
  NE: number;
  URL: string;

  tipo_estudo: string;
  data_publ: string;
}


export const articleAttributesMapping = {
  semana: 'SEM.',
  data_informe: 'DATA do INFORME',
  ID: 'ID',
  excluir: 'EXCLUIR?',
  autores: 'AUTORES',
  titulo: 'TÍTULO',
  tecnologias: 'ESPECIFICAÇÃO da TECNOLOGIA',
  sumario_achados: 'SUMÁRIO dos ACHADOS',
  aval_qual_metod: 'AVALIAÇÃO da QUALIDADE METODOLÓGICA',
  resumo: 'RESUMO',
  referencia_bibliografica: 'REFERÊNCIA (Vancouver)',
  país: 'PAÍS',
  NE: 'NÍVEL de EVIDÊNCIA',
  URL: 'URL',

  tipo_estudo: 'TIPO de ESTUDO',
  data_publ: 'DATA PUBL',
};

Thank you very much for your time!
José

Accented characters, are they alowed?

Hi!

I'm having dificulty acessing columns with accented characteres like "TÍTULO". Is this supported or must headers be free of this kind of characteres like 'á'?

Here is my entity and attributes mapping structures.

export interface Article {
  semana: number;
  data_informe: string;
  ID: string;
  excluir: string;
  autores: string;
  tipo_estudo: string;
  data_publ: string;
  tecnologias: string;
  //titulo: string;
}

export const articleAttributesMapping = {
  semana: 'SEM.',
  data_informe: "DATA do INFORME",
  ID: 'ID',
  EXCLUIR: 'EXCLUIR?',
  autores: 'AUTORES',
  tipo_estudo: 'TIPO de ESTUDO',
  titulo: 'TITULO',
  data_publ: 'DATA PUBL',
  tecnologias: 'ESPECIFICAÇÃO da TECNOLOGIA',
};

Thanks for all the help you can provide!

CORS Issue

I am getting a CORS error trying to make a request from localhost. Also how should you publish the spreadsheet? Website, csv, ....?

Loading rows in batches

Hey @FranzDiebold

Great work on the library!
Wanted to know if there's a way we can fetch only a few rows at a time.

My Use Case:
I have a very large sheet (about 5,000 rows). And I want to display data of only 10 rows at a time.
Following a trigger, I would want to load the next 10 rows and so on...

Is that possible using this library?

Error while installing package to angular 13

Please help to get it resolve. Thanks

npm ERR! While resolving: [email protected]
npm ERR! Found: @angular/[email protected]
npm ERR! node_modules/@angular/common
npm ERR! @angular/common@"~13.3.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"^10.2.5" from [email protected]
npm ERR! node_modules/ng-google-sheets-db
npm ERR! ng-google-sheets-db@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Get sheet data without Active field

Hey, firstly brilliant project.
My question is that in

this.googleSheetsDbService
    .getActive(
      'sheetID', 
      'SheetName', 
      AttributesMapping, 
      'Active'
 );

is Active required??
What if I don't want active column in google sheet and get all rows?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.