Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trust relationships ordering update #493

Merged
merged 4 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 27 additions & 13 deletions server/handlers/walletHandler/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,42 +74,56 @@ const walletGetTrustRelationships = async (req, res) => {
});
const validatedQuery = await walletGetTrustRelationshipsSchema.validateAsync(
req.query,
{ abortEarly: false },
{
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we shourd force code format on committing, so it makes review easier

abortEarly: false,
},
);
const walletService = new WalletService();

const { wallet_id: walletId } = validatedParams;
const { wallet_id: loggedInWalletId } = req;
const sortBy = 'created_at';
const orderBy = 'desc';
const { state, type, request_type, limit, offset, sort_by, order, search } = validatedQuery;
const sortBy = 'created_at';
const orderBy = 'desc';
const {
state,
type,
request_type,
limit,
offset,
sort_by,
order,
search,
} = validatedQuery;

const { wallets:managedWallets } = await walletService.getAllWallets(
const { wallets: managedWallets } = await walletService.getAllWallets(
loggedInWalletId,
{
limit:'10',
offset:'0',
limit: '1000',
offset: '0',
},
null,
sortBy,
orderBy,
null,
null
null,
);
const trustService = new TrustService();
const {result: trust_relationships, count: total} = await trustService.getTrustRelationships(
const {
result: trust_relationships,
count: total,
} = await trustService.getTrustRelationships(
loggedInWalletId,
managedWallets,
{
walletId,
state,
type,
request_type,
limit,
offset,
sort_by,
limit,
offset,
sort_by,
order,
search
search,
},
);
res.status(200).json({
Expand Down
31 changes: 22 additions & 9 deletions server/models/Trust.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class Trust {
*/
async getTrustRelationships({
walletId,
managedWallets=[],
managedWallets = [],
state,
type,
request_type,
Expand All @@ -55,13 +55,14 @@ class Trust {
search,
order,
}) {
const managedWalletIds = managedWallets.map(wallet => wallet.id);
const managedWalletIds = managedWallets.map((wallet) => wallet.id);

const orConditions = [
{ actor_wallet_id: walletId },
{ target_wallet_id: walletId },
{ originator_wallet_id: walletId },
];

managedWalletIds.forEach((managedWalletId) => {
orConditions.push({ actor_wallet_id: managedWalletId });
orConditions.push({ target_wallet_id: managedWalletId });
Expand Down Expand Up @@ -92,9 +93,19 @@ class Trust {
],
});
}
return this._trustRepository.getByFilter(filter, { offset, limit, sort_by, order });
return this._trustRepository.getByFilter(
filter,
{
offset,
limit,
sort_by,
order,
},
walletId,
managedWalletIds,
);
}

async getTrustRelationshipsCount({ walletId, state, type, request_type }) {
const filter = Trust.getTrustRelationshipFilter({
walletId,
Expand Down Expand Up @@ -235,8 +246,8 @@ class Trust {
// check if I (current wallet) can add a new trust like this
async checkDuplicateRequest({ walletId, trustRelationship }) {
let trustRelationships = await this.getTrustRelationships({ walletId });
if (trustRelationships.result) {
trustRelationships = trustRelationships.result;
if (trustRelationships.result) {
trustRelationships = trustRelationships.result;
}
if (
trustRelationship.type ===
Expand Down Expand Up @@ -380,8 +391,10 @@ class Trust {

async updateTrustState(trustRelationship, state) {
const trustRelationshipToUpdate = { ...trustRelationship };
const now = new Date();
const formattedDate = `${(now.getMonth() + 1).toString().padStart(2, '0')}/${now
const now = new Date();
const formattedDate = `${(now.getMonth() + 1)
.toString()
.padStart(2, '0')}/${now
.getDate()
.toString()
.padStart(2, '0')}/${now.getFullYear()}`;
Expand Down
79 changes: 47 additions & 32 deletions server/models/Trust.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,19 @@ describe('Trust Model', () => {

describe('getTrustRelationships', () => {
const walletId = uuid();
const managedWallets = [{id: '90f8b2ab-c101-405d-922a-0a64dbe64ab6'}];
const managedWalletIds = managedWallets.map(wallet => wallet.id);
const orConditions = [
{ actor_wallet_id: walletId },
{ target_wallet_id: walletId },
{ originator_wallet_id: walletId },
];

managedWalletIds.forEach((managedWalletId) => {
orConditions.push({ actor_wallet_id: managedWalletId });
orConditions.push({ target_wallet_id: managedWalletId });
orConditions.push({ originator_wallet_id: managedWalletId });
});
const managedWallets = [{ id: '90f8b2ab-c101-405d-922a-0a64dbe64ab6' }];
const managedWalletIds = managedWallets.map((wallet) => wallet.id);
const orConditions = [
{ actor_wallet_id: walletId },
{ target_wallet_id: walletId },
{ originator_wallet_id: walletId },
];

managedWalletIds.forEach((managedWalletId) => {
orConditions.push({ actor_wallet_id: managedWalletId });
orConditions.push({ target_wallet_id: managedWalletId });
orConditions.push({ originator_wallet_id: managedWalletId });
});
const filter = {
and: [
{
Expand All @@ -50,7 +50,7 @@ describe('Trust Model', () => {

it('should get relationships', async () => {
trustRepositoryStub.getByFilter.resolves(['relationship1']);

const result = await trustModel.getTrustRelationships({
managedWallets,
walletId,
Expand All @@ -59,12 +59,17 @@ describe('Trust Model', () => {
offset: 1,
});
expect(result).eql(['relationship1']);
expect(trustRepositoryStub.getByFilter).calledOnceWithExactly(filter, {
limit: 10,
offset: 1,
order: undefined,
sort_by: undefined
});
expect(trustRepositoryStub.getByFilter).calledOnceWithExactly(
filter,
{
limit: 10,
offset: 1,
order: undefined,
sort_by: undefined,
},
walletId,
managedWalletIds,
);
});

it('should get relationships -- state', async () => {
Expand All @@ -85,8 +90,10 @@ describe('Trust Model', () => {
limit: 10,
offset: 1,
order: undefined,
sort_by: undefined
sort_by: undefined,
},
walletId,
managedWalletIds,
);
});

Expand All @@ -109,8 +116,10 @@ describe('Trust Model', () => {
limit: 10,
offset: 11,
order: undefined,
sort_by: undefined
sort_by: undefined,
},
walletId,
managedWalletIds,
);
});

Expand All @@ -133,8 +142,10 @@ describe('Trust Model', () => {
limit: 101,
offset: 1,
order: undefined,
sort_by: undefined
sort_by: undefined,
},
walletId,
managedWalletIds,
);
});

Expand All @@ -161,8 +172,10 @@ describe('Trust Model', () => {
limit: 100,
offset: 0,
order: undefined,
sort_by: undefined
sort_by: undefined,
},
walletId,
managedWalletIds,
);
});
});
Expand Down Expand Up @@ -739,13 +752,14 @@ describe('Trust Model', () => {
it('updateTrustState', async () => {
trustRepositoryStub.update.resolves({ status: 'updated' });

const now = new Date();
const formattedDate = `${(now.getMonth() + 1).toString().padStart(2, '0')}/${now
const now = new Date();
const formattedDate = `${(now.getMonth() + 1)
.toString()
.padStart(2, '0')}/${now
.getDate()
.toString()
.padStart(2, '0')}/${now.getFullYear()}`;


const result = await trustModel.updateTrustState(
{
id: 'trustId',
Expand All @@ -767,7 +781,7 @@ describe('Trust Model', () => {
expect(trustRepositoryStub.update).calledOnceWithExactly({
id: 'trustId',
state: 'new state',
updated_at: formattedDate
updated_at: formattedDate,
});
});

Expand Down Expand Up @@ -910,7 +924,7 @@ describe('Trust Model', () => {
});

it('should error out -- no permission to accept', async () => {
trustRepositoryStub.getByFilter.resolves({count: 0, result: []});
trustRepositoryStub.getByFilter.resolves({ count: 0, result: [] });
const trustRelationshipId = uuid();
const walletId = uuid();

Expand Down Expand Up @@ -938,9 +952,10 @@ describe('Trust Model', () => {
const trustRelationshipId = uuid();
const walletId = uuid();

trustRepositoryStub.getByFilter.resolves({count: 1, result:[
{ originator_wallet_id: walletId, id: trustRelationshipId },
]});
trustRepositoryStub.getByFilter.resolves({
count: 1,
result: [{ originator_wallet_id: walletId, id: trustRelationshipId }],
});
updateTrustStateStub.resolves('state cancelled');
const result = await trustModel.cancelTrustRequest({
trustRelationshipId,
Expand Down
50 changes: 38 additions & 12 deletions server/repositories/TrustRepository.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,12 @@ class TrustRepository extends BaseRepository {
return list;
}

async getByFilter(filter, limitOptions) {
async getByFilter(
filter,
limitOptions = {},
loggedInWalletId = '',
managedWalletIds = [],
) {
let promise = this._session
.getDB()
.select(
Expand Down Expand Up @@ -68,15 +73,7 @@ class TrustRepository extends BaseRepository {
)
.where((builder) => this.whereBuilder(filter, builder));

const count = await this._session.getDB().from(promise.as('p')).count('*');

if (limitOptions && limitOptions.limit) {
promise = promise.limit(limitOptions.limit);
}

if (limitOptions && limitOptions.offset) {
promise = promise.offset(limitOptions.offset);
}
const count = await this._session.getDB().from(promise.as('p')).count('*');

let order = 'desc';
let column = 'created_at';
Expand All @@ -98,9 +95,38 @@ class TrustRepository extends BaseRepository {
promise = promise.offset(limitOptions.offset);
}
}
promise = promise.orderBy(column, order);

const result = await promise;
// order by new column priority
// priority is 1 when state is requested and
// target is current wallet or one of its managed wallets
if (managedWalletIds.length > 0 && loggedInWalletId) {
promise = promise.select(
this._session.getDB().raw(
`CASE
WHEN wallet_trust.state = 'requested' AND
(wallet_trust.target_wallet_id = ? OR wallet_trust.target_wallet_id IN (${managedWalletIds
.map(() => '?')
.join(',')})) THEN 1
ELSE 0
END AS priority`,
[loggedInWalletId, ...managedWalletIds],
),
);
promise = promise.orderBy([
{ column: 'priority', order: 'desc' },
{ column, order }, // secondary
{ column: 'id', order }, // tertiary sort, prevent duplicate records among pages
]);
} else {
// normal ordering for other endpoints
promise = promise.orderBy(column, order);
}

let result = await promise;

// remove priority column from result
// eslint-disable-next-line no-unused-vars
result = result.map(({ priority, ...rest }) => rest);

return { result, count: +count[0].count };
}
Expand Down
Loading
Loading