diff --git a/keyserver/src/creators/thread-creator.js b/keyserver/src/creators/thread-creator.js --- a/keyserver/src/creators/thread-creator.js +++ b/keyserver/src/creators/thread-creator.js @@ -32,6 +32,7 @@ checkThreadPermission, validateCandidateMembers, } from '../fetchers/thread-permission-fetchers'; +import { personalThreadQuery } from '../search/threads'; import type { Viewer } from '../session/viewer'; import { changeRole, @@ -233,17 +234,7 @@ otherMemberID, 'Other member id should be set for a PERSONAL thread', ); - existingThreadQuery = SQL` - SELECT t.id - FROM threads t - INNER JOIN memberships m1 - ON m1.thread = t.id AND m1.user = ${viewer.userID} - INNER JOIN memberships m2 - ON m2.thread = t.id AND m2.user = ${otherMemberID} - WHERE t.type = ${threadTypes.PERSONAL} - AND m1.role > 0 - AND m2.role > 0 - `; + existingThreadQuery = personalThreadQuery(viewer.userID, otherMemberID); } else if (sourceMessageID) { existingThreadQuery = SQL` SELECT t.id diff --git a/keyserver/src/search/threads.js b/keyserver/src/search/threads.js new file mode 100644 --- /dev/null +++ b/keyserver/src/search/threads.js @@ -0,0 +1,34 @@ +// @flow + +import type { QueryResults } from 'mysql'; + +import { threadTypes } from 'lib/types/thread-types'; + +import { dbQuery, SQL } from '../database/database'; + +function personalThreadQuery( + firstMemberID: string, + secondMemberID: string, +): any { + return SQL` + SELECT t.id + FROM threads t + INNER JOIN memberships m1 + ON m1.thread = t.id AND m1.user = ${firstMemberID} + INNER JOIN memberships m2 + ON m2.thread = t.id AND m2.user = ${secondMemberID} + WHERE t.type = ${threadTypes.PERSONAL} + AND m1.role > 0 + AND m2.role > 0 + `; +} + +async function searchForPersonalThread( + viewerID: string, + otherMemberID: string, +): Promise { + const query = personalThreadQuery(viewerID, otherMemberID); + return await dbQuery(query); +} + +export { personalThreadQuery, searchForPersonalThread };