In my quest to create a function that validates the userId or channelId, I am looping through the data store provided below.
let data = {
users: [
{
uId: 1,
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b70727d5b70767a727735787476">[email protected]</a>',
password: 'kif123',
nameFirst: 'Kifaya',
nameLast: 'Shehadeh',
handle: 'kifayashehadeh',
},
{
uId: 2,
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="69101c1a291004080005470a0604">[email protected]</a>',
password: 'yus1234',
nameFirst: 'Yusra',
nameLast: 'Mahomed',
handle: 'yusramahomed',
},
],
channels: [
{
channelId: 1,
name: 'DREAM',
ownerMembers: [1,2,3,4,5],
allMembers: [1,2,3,4,5],
isPublic: false,
messages: [
{
messageId: 1,
uId: 1,
message: "Coffee is better at 12am.",
timeSent: Math.floor((new Date()).getTime() / 1000),
},
{
messageId: 2,
uId: 2,
message: "Chocolate is better 24/7.",
timeSent: Math.floor((new Date()).getTime() / 1000),
},
],
},
{
channelId: 2,
name: 'COFFEE',
ownerMembers: [1,2],
allMembers: [1,2,3,4,5],
isPublic: true,
messages: [
{
messageId: 1,
uId: 4,
message: "Dark chocolate isn't even chocolate. Seriously.",
timeSent: Math.floor((new Date()).getTime() / 1000),
},
],
},
],
};
My current approach within the function involves:
//invalid channelId
let error = true;
for (const channel of data.channels) {
if (channel.channelId !== channelId ) {
error = false;
}
}
//invalid user
for (const user of data.users) {
if (user.uId === authUserId) {
error = false;
}
}
if (error === true) {
return {
error : 'error'
}
}
This process feels rather inefficient and more akin to C than javascript. Is there an elegant one-liner that can handle this without sacrificing readability? Additionally, I'm struggling with implementing proper error checking logic. How can I immediately return an error and exit the function upon detection?