Skip to content

Commit

Permalink
fix: get returns undefined when index used does not exist
Browse files Browse the repository at this point in the history
  • Loading branch information
dafuga committed Jan 4, 2024
1 parent 40c5c30 commit 691d971
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
19 changes: 16 additions & 3 deletions src/contract/table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export class Table<RowType = any> {
* Each key-value pair in the queryParams object corresponds to a field and its expected value in the table.
* @returns {Promise<TableRow>} Promise resolving to a single table row.
*/
async get(value?: API.v1.TableIndexType | string, params: QueryParams = {}): Promise<RowType> {
async get(value?: API.v1.TableIndexType | string, params: QueryParams = {}): Promise<RowType | undefined> {
const tableRowsParams: any = {
table: this.name,
code: this.account,
Expand Down Expand Up @@ -186,8 +186,21 @@ export class Table<RowType = any> {
tableRowsParams.index_position = fieldToIndexMapping[params.index].index_position
}

const {rows} = await this.client!.v1.chain.get_table_rows(tableRowsParams)
let [row] = rows
let row

try {
const {rows} = await this.client!.v1.chain.get_table_rows(tableRowsParams)

row = rows[0]
} catch (error: unknown) {
const message = (error as { message }).message

if (message.includes('No data')) {
return
} else {
throw error
}
}

if (!this.rowType) {
row = Serializer.decode({
Expand Down
10 changes: 8 additions & 2 deletions test/tests/table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ suite('Table', () => {
assert.instanceOf(table, Table)
const row = await table.get()
assert.instanceOf(row, NameBid)
assert.instanceOf(row.newname, Name)
assert.instanceOf(row.high_bid, Int64)
assert.instanceOf(row?.newname, Name)
assert.instanceOf(row?.high_bid, Int64)
})
suite('all', () => {
test('should return every single row in a table', async () => {
Expand Down Expand Up @@ -388,6 +388,12 @@ suite('Table', () => {
const result = await contract.table('accounts', 'wharfkittest').get()
assert.instanceOf(result.balance, Asset)
})

test('should return undefined when no entry is found', async function () {
const row = await producersTable.get('doesnotexist')

assert.isUndefined(row)
})
})

suite('first', () => {
Expand Down

0 comments on commit 691d971

Please sign in to comment.