Skip to content

Commit

Permalink
insertDimension cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Theo Ephraim committed Nov 6, 2021
1 parent 6a4a9b9 commit 71cf945
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 34 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ module.exports = {
exports: 'always-multiline',
functions: 'never', // this breaks
}],
'no-multiple-empty-lines': 0, // sometimes helpful to break up sections of code
},
overrides: [
{ // extra jest related rules for tests
Expand Down
13 changes: 7 additions & 6 deletions docs/classes/google-spreadsheet-worksheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,19 +244,20 @@ Param|Type|Required|Description

-**Side effects** - sheet is updated

#### `insertDimension(columnsOrRows, bounds, inheritFromBefore)` (async) :id=fn-insertDimension
#### `insertDimension(columnsOrRows, range, inheritFromBefore)` (async) :id=fn-insertDimension

> Update sheet "dimension properties"
| Param | Type | Required | Description |
| --- | --- | --- | --- |
| `columnsOrRows` | String (enum)<br>_"COLUMNS" or "ROWS"_ || Which dimension |
| `bounds` | Object | - |
| `bounds.startIndex` | Number<br>_int >= 0_ | - | Start row/column |
| `bounds.endIndex` | Number<br>_int >= 0_ | - | End row/column |
| `inheritFromBefore` | Boolean<br>_default false_ | - | If true, tells the API to give the new columns or rows the same properties as the prior row or column |
| `range` | Object | |
| `range.startIndex` | Number<br>_int >= 0_ | | Start row/column (inclusive) |
| `range.endIndex` | Number<br>_int >= 1_ | | End row/column (exclusive), must be greater than startIndex |
| `inheritFromBefore` | Boolean<br>_default true_ | - | If true, tells the API to give the new columns or rows the same properties as the prior row or column<br>NOTE - defaults to false if inserting in first row/column |

-**Side effects** - sheet is updated
-**Side effects** - new row(s) or column(s) are inserted into the sheet
- 🚨 **Warning** - Does not update cached rows/cells, so be sure to reload rows/cells before trying to make any updates to sheet contents

### Other

Expand Down
1 change: 0 additions & 1 deletion lib/GoogleSpreadsheetCell.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,6 @@ class GoogleSpreadsheetCell {
delete (format.backgroundColorStyle);
}


return {
updateCells: {
rows: [{
Expand Down
26 changes: 17 additions & 9 deletions lib/GoogleSpreadsheetWorksheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,6 @@ class GoogleSpreadsheetWorksheet {
return this._cells[rowIndex][columnIndex];
}


async loadCells(sheetFilters) {
// load the whole sheet
if (!sheetFilters) return this._spreadsheet.loadCells(this.a1SheetName);
Expand Down Expand Up @@ -283,7 +282,6 @@ class GoogleSpreadsheetWorksheet {
// });
// }


// ROW BASED FUNCTIONS ///////////////////////////////////////////////////////////////////////////

async loadHeaderRow() {
Expand Down Expand Up @@ -632,22 +630,32 @@ class GoogleSpreadsheetWorksheet {
// https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#FindReplaceRequest
}

async insertDimension(columnsOrRows, bounds, inheritFromBefore = false) {
async insertDimension(columnsOrRows, range, inheritFromBefore = null) {
// Request type = `insertDimension`
// https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#InsertDimensionRequest

if (!columnsOrRows) {
throw new Error('You need to specify a dimension. i.e. COLUMNS|ROWS');
if (!columnsOrRows) throw new Error('You need to specify a dimension. i.e. COLUMNS|ROWS');
if (!_.isObject(range)) throw new Error('`range` must be an object containing `startIndex` and `endIndex`');
if (!_.isInteger(range.startIndex) || range.startIndex < 0) throw new Error('range.startIndex must be an integer >=0');
if (!_.isInteger(range.endIndex) || range.endIndex < 0) throw new Error('range.endIndex must be an integer >=0');
if (range.endIndex <= range.startIndex) throw new Error('range.endIndex must be greater than range.startIndex');

// default inheritFromBefore to true - unless inserting in the first row/column
if (inheritFromBefore === null) {
inheritFromBefore = range.startIndex > 0;
}

// do not allow inheritFromBefore if inserting at first row/column
if (inheritFromBefore && range.startIndex === 0) {
throw new Error('Cannot set inheritFromBefore to true if inserting in first row/column');
}

return this._makeSingleUpdateRequest('insertDimension', {
range: {
sheetId: this.sheetId,
dimension: columnsOrRows,
...bounds && {
startIndex: bounds.startIndex,
endIndex: bounds.endIndex,
},
startIndex: range.startIndex,
endIndex: range.endIndex,
},
inheritFromBefore,
});
Expand Down
2 changes: 1 addition & 1 deletion test/cells.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const _ = require('lodash');
const delay = require('delay');

const { GoogleSpreadsheetFormulaError } = require('../index.js');
const { GoogleSpreadsheetFormulaError } = require('../index');

const docs = require('./load-test-docs')();
const creds = require('./service-account-creds.json');
Expand Down
48 changes: 31 additions & 17 deletions test/manage.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const delay = require('delay');
const _ = require('lodash');

const { GoogleSpreadsheet, GoogleSpreadsheetWorksheet } = require('../index.js');
const { GoogleSpreadsheet, GoogleSpreadsheetWorksheet } = require('../index');

const docs = require('./load-test-docs')();
const creds = require('./service-account-creds.json');
Expand All @@ -16,6 +16,14 @@ describe('Managing doc info and sheets', () => {
// hitting rate limits when running tests on ci - so we add a short delay
if (process.env.NODE_ENV === 'ci') afterEach(async () => delay(500));

/* eslint-disable jest/no-commented-out-tests */
// uncomment temporarily to clear out all the sheets in the test doc
// it.only('clear out all the existing sheets', async () => {
// await doc.loadInfo();
// // delete all sheets after the first
// for (const sheet of doc.sheetsByIndex.slice(1)) await sheet.delete();
// });

describe('accessing and updating document properties', () => {
it('accessing properties throws an error if info not fetched yet', async () => {
expect(() => doc.title).toThrow();
Expand Down Expand Up @@ -50,7 +58,7 @@ describe('Managing doc info and sheets', () => {

it('can update the title using updateProperties', async () => {
const oldTitle = doc.title;
const newTitle = `${doc.title} updated @ ${+new Date()}`;
const newTitle = `node-google-spreadsheet test - private (updated @ ${+new Date()})`;
await doc.updateProperties({ title: newTitle });
expect(doc.title).toBe(newTitle);

Expand Down Expand Up @@ -239,35 +247,41 @@ describe('Managing doc info and sheets', () => {
});
});

describe('Insert a column or row to a document', () => {
describe('insertDimension - inserting columns/rows into a sheet', () => {
let sheet;

beforeAll(async () => {
sheet = await doc.addSheet({
title: `Sheet to copy ${+new Date()}`,
title: `Insert dimension test ${+new Date()}`,
headerValues: ['a', 'b'],
});
await sheet.addRow({
a: 'a',
b: 'b',
});
await sheet.addRows([
{ a: 'a1', b: 'b1' },
{ a: 'a2', b: 'b2' },
]);
});

afterAll(async () => {
await sheet.delete();
});

it('Should insert a new empty row at index', async () => {
await sheet.insertDimension('ROWS', {
startIndex: 1,
endIndex: 2,
});
// TODO: add error checking tests

// read rows
const rows = await sheet.getRows();
it('Should insert a new empty rows at index', async () => {
// should insert 2 rows in between the first and second row of data (first row is header)
await sheet.insertDimension('ROWS', { startIndex: 2, endIndex: 4 });

expect(rows[0].a).toEqual('');
expect(rows[0].b).toEqual('');
// read rows and check it did what we expected
const rows = await sheet.getRows();
// header row
expect(rows[0].a).toEqual('a1');
expect(rows[0].b).toEqual('b1');
expect(rows[1].a).toBeUndefined();
expect(rows[1].b).toBeUndefined();
expect(rows[2].a).toBeUndefined();
expect(rows[2].b).toBeUndefined();
expect(rows[3].a).toEqual('a2');
expect(rows[3].b).toEqual('b2');
});
});
});

0 comments on commit 71cf945

Please sign in to comment.