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 @@ -27,7 +27,10 @@ import { dbQuery, SQL } from '../database/database'; import { fetchMessageInfoByID } from '../fetchers/message-fetchers'; -import { determineThreadAncestry } from '../fetchers/thread-fetchers'; +import { + determineThreadAncestry, + personalThreadQuery, +} from '../fetchers/thread-fetchers'; import { checkThreadPermission, validateCandidateMembers, @@ -233,17 +236,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/fetchers/thread-fetchers.js b/keyserver/src/fetchers/thread-fetchers.js --- a/keyserver/src/fetchers/thread-fetchers.js +++ b/keyserver/src/fetchers/thread-fetchers.js @@ -1,5 +1,7 @@ // @flow +import type { QueryResults } from 'mysql'; + import { getAllThreadPermissions } from 'lib/permissions/thread-permissions'; import { rawThreadInfoFromServerThreadInfo, @@ -214,6 +216,31 @@ return { containingThreadID, community, depth }; } +function personalThreadQuery( + firstMemberID: string, + secondMemberID: string, +): SQLStatementType { + 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 fetchPersonalThreadID( + viewerID: string, + otherMemberID: string, +): Promise { + const query = personalThreadQuery(viewerID, otherMemberID); + return await dbQuery(query); +} + export { fetchServerThreadInfos, fetchThreadInfos, @@ -221,4 +248,6 @@ verifyThreadIDs, verifyThreadID, determineThreadAncestry, + personalThreadQuery, + fetchPersonalThreadID, };