Skip to content

Instantly share code, notes, and snippets.

@supertopoz
Created November 5, 2020 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save supertopoz/dbfdcb5220307e4bf965fd12c388a016 to your computer and use it in GitHub Desktop.
Save supertopoz/dbfdcb5220307e4bf965fd12c388a016 to your computer and use it in GitHub Desktop.
class SearchMembers {
constructor(channel) {
this.targetChannel = channel;
this.dictionary = {};
}
addQueryUsersToDictionary(users, searchTerm) {
if (users.length === 0) {
this.dictionary[searchTerm] = {};
return;
}
users.forEach((user) => {
for (var i = 1; i <= 10; i++) {
let dictionaryKey = user.nickname.slice(0, i).toLowerCase();
const userId = user.userId;
let entry = {};
entry[userId] = user;
if (this.dictionary[dictionaryKey]) {
entry = this.dictionary[dictionaryKey];
entry[userId] = user;
}
this.dictionary[dictionaryKey] = entry;
}
});
}
querySendbirdForNicknames(searchTerm) {
return new Promise((resolve, reject) => {
let query = this.targetChannel.createMemberListQuery();
query.nicknameStartsWithFilter = searchTerm;
query.limit = 100;
const fetch = () => {
if (query.hasNext) {
query.next((users, error) => {
if (error) reject(error);
this.addQueryUsersToDictionary(users, searchTerm);
fetch();
});
} else {
resolve(this.dictionary);
}
};
fetch();
});
}
searchChannelMembers(searchTerm) {
return new Promise((resolve, reject) => {
if (searchTerm.length <= 1) reject(null);
if (this.dictionary[searchTerm]) {
console.log("CALLED_IN");
resolve(this.dictionary[searchTerm]);
return;
}
console.log("CALLED OUT");
this.querySendbirdForNicknames(searchTerm)
.then((dictionary) => {
resolve(dictionary[searchTerm]);
})
.catch((error) => {
reject(error);
});
});
}
}
export default SearchMembers;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment