Skip to content

Commit

Permalink
bunch of fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
theoephraim committed Feb 28, 2020
1 parent a6baa65 commit dc38223
Show file tree
Hide file tree
Showing 11 changed files with 35 additions and 21 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ More info:
### Working with rows
```javascript
// create a sheet and set the header row
const sheet = await doc.addSheet({ headers: ['name', 'email'] });
const sheet = await doc.addSheet({ headerValues: ['name', 'email'] });

// append rows
const larryRow = await sheet.addRow({ name: 'Larry Page', email: 'larry@google.com' });
Expand Down
2 changes: 1 addition & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ More info:
### Working with rows
```javascript
// create a sheet and set the header row
const sheet = await doc.addSheet({ headers: ['name', 'email'] });
const sheet = await doc.addSheet({ headerValues: ['name', 'email'] });

// append rows
const larryRow = await sheet.addRow({ name: 'Larry Page', email: 'larry@google.com' });
Expand Down
2 changes: 1 addition & 1 deletion docs/classes/google-spreadsheet-row.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Google uses both row/column indices and A1-style notation, available as **read-o

Property|Type|Description
---|---|---
`rowIndex`|Number<br>_int >= 0_|Row number in the sheet of this row
`rowNumber`|Number<br>_int >= 1_|A1 row number in the sheet of this row
`a1Range`|String|Full A1 range of this row, including the sheet name<br>_Ex: "sheet1!A5:D5"_

### Row Values
Expand Down
2 changes: 1 addition & 1 deletion docs/classes/google-spreadsheet-worksheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ Param|Type|Required|Description


#### `getCell(rowIndex, columnIndex)` :id=fn-getCell
> retrieve a cell from the cache based on A1 address
> retrieve a cell from the cache based on zero-indexed row/column
Param|Type|Required|Description
---|---|---|---
Expand Down
7 changes: 4 additions & 3 deletions lib/GoogleSpreadsheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,15 +249,16 @@ class GoogleSpreadsheet {
// https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddSheetRequest

const response = await this._makeSingleUpdateRequest('addSheet', {
properties: _.omit(properties, 'headers'),
properties: _.omit(properties, 'headers', 'headerValues'),
});
// _makeSingleUpdateRequest already adds the sheet
const newSheetId = response.properties.sheetId;
const newSheet = this.sheetsById[newSheetId];

// allow it to work with `.headers` but `.headerValues` is the real prop
if (properties.headers) { await newSheet.setHeaderRow(properties.headers); }
if (properties.headerValues) { await newSheet.setHeaderRow(properties.headerValues); }
if (properties.headerValues || properties.headers) {
await newSheet.setHeaderRow(properties.headerValues || properties.headers);
}

return newSheet;
}
Expand Down
2 changes: 2 additions & 0 deletions lib/GoogleSpreadsheetRow.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ class GoogleSpreadsheetRow {
return this;
}

get rowNumber() { return this._rowNumber; }
// TODO: deprecate rowIndex - the name implies it should be zero indexed :(
get rowIndex() { return this._rowNumber; }
get a1Range() {
return [
Expand Down
22 changes: 15 additions & 7 deletions lib/GoogleSpreadsheetWorksheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ class GoogleSpreadsheetWorksheet {
set rowCount(newVal) { throw new Error('Do not update directly. Use resize()'); }
set columnCount(newVal) { throw new Error('Do not update directly. Use resize()'); }

get a1SheetName() { return `'${this.title}'`; }
get a1SheetName() { return `'${this.title.replace(/'/g, "''")}'`; }
get encodedA1SheetName() { return encodeURIComponent(this.a1SheetName); }
get lastColumnLetter() { return columnToLetter(this.columnCount); }


Expand Down Expand Up @@ -311,13 +312,13 @@ class GoogleSpreadsheetWorksheet {

const response = await this._spreadsheet.axios.request({
method: 'put',
url: `/values/${encodeURIComponent(this.a1SheetName)}!A1`,
url: `/values/${this.encodedA1SheetName}!1:1`,
params: {
valueInputOption: 'USER_ENTERED', // other option is RAW
includeValuesInResponse: true,
},
data: {
range: `${this.a1SheetName}!A1`,
range: `${this.a1SheetName}!1:1`,
majorDimension: 'ROWS',
values: [[
...trimmedHeaderValues,
Expand All @@ -338,6 +339,12 @@ class GoogleSpreadsheetWorksheet {
// an object must use the header row values as keys
// ex: { col1: 'column 1', col2: 'column 2', col3: 'column 3' }

// google bug that does not handle colons in names
// see https://issuetracker.google.com/issues/150373119
if (this.title.includes(':')) {
throw new Error('Please remove the ":" from your sheet title. There is a bug with the google API which breaks appending rows if any colons are in the sheet title.');
}

if (!_.isArray(rows)) throw new Error('You must pass in an array of row values to append');

if (!this.headerValues) await this.loadHeaderRow();
Expand All @@ -362,7 +369,7 @@ class GoogleSpreadsheetWorksheet {

const response = await this._spreadsheet.axios.request({
method: 'post',
url: `/values/${encodeURIComponent(this.a1SheetName)}:append`,
url: `/values/${this.encodedA1SheetName}:append`,
params: {
valueInputOption: options.raw ? 'RAW' : 'USER_ENTERED',
insertDataOption: options.insert ? 'INSERT_ROWS' : 'OVERWRITE',
Expand All @@ -383,7 +390,8 @@ class GoogleSpreadsheetWorksheet {
if (options.insert) {
this._rawProperties.gridProperties.rowCount += rows.length;
} else if (rowNumber + rows.length > this.rowCount) {
this._rawProperties.gridProperties.rowCount = rowNumber + rows.length;
// have to subtract 1 since one row was inserted at rowNumber
this._rawProperties.gridProperties.rowCount = rowNumber + rows.length - 1;
}

return _.map(response.data.updates.updatedData.values, (rowValues) => {
Expand Down Expand Up @@ -504,7 +512,7 @@ class GoogleSpreadsheetWorksheet {
// this uses the "values" getter and does not give all the info about the cell contents
// it is used internally when loading header cells
async getCellsInRange(a1Range, options) {
const response = await this._spreadsheet.axios.get(`/values/${encodeURIComponent(this.a1SheetName)}!${a1Range}`, {
const response = await this._spreadsheet.axios.get(`/values/${this.encodedA1SheetName}!${a1Range}`, {
params: options,
});
return response.data.values;
Expand Down Expand Up @@ -796,7 +804,7 @@ class GoogleSpreadsheetWorksheet {
async clear() {
// clears all the data in the sheet
// sheet name without ie 'sheet1' rather than 'sheet1'!A1:B5 is all cells
await this._spreadsheet.axios.post(`/values/${encodeURIComponent(this.a1SheetName)}:clear`);
await this._spreadsheet.axios.post(`/values/${this.encodedA1SheetName}:clear`);
this.resetLocalCache(true);
}
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"author": "Theo Ephraim <theozero@gmail.com> (https://theoephraim.com)",
"name": "google-spreadsheet",
"description": "Google Sheets API (v4) -- simple interface to read/write data and manage sheets",
"version": "3.0.8",
"version": "3.0.9",
"license": "Unlicense",
"keywords": [
"google spreadsheets",
Expand Down
2 changes: 1 addition & 1 deletion test/cells.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe('Cell-based operations', () => {
rowCount: NUM_ROWS,
columnCount: NUM_COLS,
},
headers: ['col1', 'col2', 'col3'],
headerValues: ['col1', 'col2', 'col3'],
});
});
afterAll(async () => {
Expand Down
4 changes: 2 additions & 2 deletions test/manage.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ describe('Managing doc info and sheets', () => {
rowCount: 7,
columnCount: 11,
},
headers: ['col1', 'col2', 'col3', 'col4', 'col5'],
headerValues: ['col1', 'col2', 'col3', 'col4', 'col5'],
});
expect(doc.sheetCount).toBe(numSheets + 1);

Expand Down Expand Up @@ -174,7 +174,7 @@ describe('Managing doc info and sheets', () => {
beforeAll(async () => {
sheet = await doc.addSheet({
title: `Sheet to copy ${+new Date()}`,
headers: ['copy', 'this', 'sheet'],
headerValues: ['copy', 'this', 'sheet'],
});
});
afterAll(async () => {
Expand Down
9 changes: 6 additions & 3 deletions test/rows.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ describe('Row-based operations', () => {
beforeAll(async () => {
await doc.useServiceAccountAuth(creds);
sheet = await doc.addSheet({
headers: HEADERS,
title: `Spécial CнArs - ${+new Date()}`, // some urls have sheet title in them
headerValues: HEADERS,
title: `Spécial CнArs ${+new Date()}`, // some urls have sheet title in them
gridProperties: { rowCount: INITIAL_ROW_COUNT },
});
await sheet.addRows(INITIAL_DATA);
Expand Down Expand Up @@ -118,8 +118,11 @@ describe('Row-based operations', () => {
numbers: '999', letters: 'ZZZ',
}));
const newRows = await sheet.addRows(dataForMoreRowsThanFit);
const updatedRowCount = sheet.rowCount;
await doc.loadInfo(); // actually reload to make sure the logic is correct
expect(sheet.rowCount).toEqual(updatedRowCount);
expect(sheet.rowCount).toBeGreaterThan(oldRowCount);
expect(newRows[newRows.length - 1].rowIndex).toEqual(sheet.rowCount - 1);
expect(newRows[newRows.length - 1].rowNumber).toEqual(sheet.rowCount);
});

it('can add rows with options.raw', async () => {
Expand Down

0 comments on commit dc38223

Please sign in to comment.