feat: filter with filterByPK

This commit is contained in:
Chareice 2021-12-12 19:57:20 +08:00
parent 90846686ac
commit 9ff6575cff
2 changed files with 43 additions and 3 deletions

View File

@ -97,6 +97,34 @@ describe('repository.find', () => {
await db.close(); await db.close();
}); });
test('find pk with filter', async () => {
const Test = db.collection({
name: 'tests',
fields: [
{ type: 'string', name: 'name' },
{ type: 'string', name: 'status' },
],
});
await db.sync();
const t1 = await Test.repository.create({
values: {
name: 't1',
status: 'draft',
},
});
const result = await Test.repository.findOne({
filterByPk: <number>t1.get('id'),
filter: {
status: 'published',
},
});
expect(result).toBeNull();
});
it('findOne', async () => { it('findOne', async () => {
const data = await User.repository.findOne({ const data = await User.repository.findOne({
filter: { filter: {

View File

@ -1,6 +1,6 @@
import { Appends, Except, FindOptions } from './repository'; import { Appends, Except, FindOptions } from './repository';
import FilterParser from './filter-parser'; import FilterParser from './filter-parser';
import { FindAttributeOptions, ModelCtor } from 'sequelize'; import { FindAttributeOptions, ModelCtor, Op } from 'sequelize';
import { Database } from './database'; import { Database } from './database';
const debug = require('debug')('noco-database'); const debug = require('debug')('noco-database');
@ -39,8 +39,20 @@ export class OptionsParser {
} }
toSequelizeParams() { toSequelizeParams() {
const filterParams = this.options?.filterByPk ? this.parseFilterByPk() : this.filterParser.toSequelizeParams(); const queryParams = this.filterParser.toSequelizeParams();
return this.parseSort(this.parseFields(filterParams));
if (this.options?.filterByPk) {
queryParams.where = {
[Op.and]: [
queryParams.where,
{
[this.model.primaryKeyAttribute]: this.options.filterByPk,
},
],
};
}
return this.parseSort(this.parseFields(queryParams));
} }
/** /**