dimanche 2 juillet 2023

SQL query performance or separation of concerns?

I'm building an app. It contains User and Post.
When any post in the application is created - I should send a notification to the admin. I've done it like this:

class PostService {
  async create(data) {
    const createdPost = await this.prisma.post.create({ // creates post
      title: data.title, 
      text: data.text
      userId: data.userId,
    });
    
    this.notificationService.notify(createdPost); // sends notification
  }
}

But also I have a case where while creating the User - the default post should be created for this new user.
And here I see 2 possible options. First one:

class UserService {
  create(data) {
    const createdUser = await this.prisma(...); // creates user
    this.postService.create({ // creates post and sends notification
      title: 'default title',
      text: 'default text',
      userId: createdUser.id,
    });
  }
}

But in this case, I have to do 2 database requests (create a user and create a post).
Trying to achieve only one request, I can do the following:

class UserService {
  create(data) {
    const created = await this.prisma.user.create({ // create user and post
      name: data.name,
      post: {
        title: 'default title',
        text: 'default text',
      }
    });
    
    this.notificationService.notify(created.post) // sends notification, logic is duplicated
  }
}

But following 2nd approach, I have to duplicate the execution of "notificationService.notify" and I find this as a drawback.

Are there any possible solutions for this problem?

Aucun commentaire:

Enregistrer un commentaire