Skip to content

Commit

Permalink
feat: add orderBy parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
lpatiny committed Jul 23, 2024
1 parent 3432e83 commit 1fef57a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/__tests__/search.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ test('number', () => {
expect(search('numberColumn:5..6', db)).toHaveLength(4);
});

test('orderBy', () => {
const db = getDB();
const result = search('numberColumn:1,2,3', db, {
orderBy: 'numberColumn DESC',
}).map((entry) => entry.numberColumn);
expect(result).toEqual([3, 3, 2, 2, 1, 1]);
});

test('errors', () => {
const db = getDB();
expect(() => search('numberColumn:>1,2', db)).toThrow(
Expand Down
10 changes: 9 additions & 1 deletion src/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import { appendSQLForCriteria } from './utils/appendSQLForCriteria';
import { parseQueryString } from './utils/parseQueryString';

export interface SearchOptions {
/**
* Specify the order of the results
* @default: ''

Check warning on line 11 in src/search.ts

View workflow job for this annotation

GitHub Actions / nodejs / lint-eslint

Invalid JSDoc tag name "default:"
*/
orderBy?: string;
/**
* The name of the table to search. If not provided and there is only a table in the database it will be sued.
*/
Expand Down Expand Up @@ -40,7 +45,7 @@ export function search(
db: Database,
options: SearchOptions = {},
): Entry[] {
const { tableName = getTableName(db), limit = 1000 } = options;
const { tableName = getTableName(db), limit = 1000, orderBy = '' } = options;
const schema = getSchema(db, tableName);
let criteria = parseQueryString(queryString);
const values = appendSQLForCriteria(criteria, schema, options);
Expand All @@ -54,6 +59,9 @@ export function search(
`WHERE ${criteria.map((criterium) => criterium.sql).join(' AND ')}`,
);
}
if (orderBy) {
sqls.push(`ORDER BY ${orderBy}`);
}
if (limit) {
sqls.push(`LIMIT ${limit}`);
}
Expand Down

0 comments on commit 1fef57a

Please sign in to comment.