+ Reply Thread
#1

I was working on a project recently that needed this twitter like mention system, at that time i had no access to the internet.

So i came up with this hackey solution (which i wanna share with u guys).
When my internet was back i looked up on google for a better solution couldn't seem to find any. So i decided to share my solution, u never can tell it might save someone hours of trying to figure out what to do

[b]REQUIREMENTS[/b]
Nodejs {>= es6},
Express,
Mongoose

[b]Note[/b]: you must already be familiar with the above.

All thanks to javascript async nature implementing this feature is kinda difficult compare to languages without the async nature
What do i mean? try this out
[code]
 class post {

   static getMention(req,res,next) {
     const reg_exp = /@\w+/g;
     const post = req.body.post;
     req.body.post = post.replace(reg_exp,(data) => {
       const username = data.slice(1);//remove @ symbol
       //query database for username and return
     });
   }
 }
[/code]

if u tried out the code above (including querying the db) it would either return "undefined" or "[object promise]".
The above solution might have worked perfectly in a language without async nature e.g PHP

Now over to the solution
[code]
class post{

  static getMentions(req,res,next) {
    return new Promise((resolve,reject)=>{
   const reg_exp = /@\w+/g;
   //get array of mentions
   const arr = req.body.post.match(reg_exp);
   arr.forEach(data=>{
     const username = data.slice(1); //remove @ symbol
  users.findOne({
       'name.user': username
     })
     .then(result => {
       arr.shift();
    if (result) {
      //find and replace mention in the post
      req.body.tweet = req.body.tweet.replace(data,()=>{
        return `<a href="/api/v1/users/${result.id}">${data}</a>`;
   });
    }
  });
   });

   setInterval(()=>{
     if (arr.length === 0) resolve();
   },100)
    })
    .then(()=>next());
 }
}
[/code]
hackey uhn!!!

i think the source code as explained it self but if u do have any difficulty with d above code,
have a better solution,
or wanna report a bug,
please drop a comment in the comment section

#2

That is very interesting, I believe this will help someone truly.

Back to top