最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - How to allow action only if all children have a status? - Stack Overflow

programmeradmin4浏览0评论

My app manage Email campaigns that we can close only if all related messages are sent.

// CampaignEntity
class CampaignEntity {
  id: number;
  messages: MessageEntity[];
  status: 'CLOSED' | 'OPEN'
}

// MessageEntity
class MessageEntity{
  id: number;
  status: 'DRAFT' | 'WAITING' | 'SENT'
}

// Allow if campaign has no messages
can(Close, CampaignEntity, {
  messages: { $size: 0 },
});

// Allow if every message status is SENT
can(Close, CampaignEntity, {
  messages: { /* all messages have status === 'SENT' */ },
});

If $not had been a valid operator, I would have used this:

can(Close, CampaignEntity, {
  messages: {
    $not: { $elemMatch: { status: { $ne: 'SENT' } } },
  },
});

My app manage Email campaigns that we can close only if all related messages are sent.

// CampaignEntity
class CampaignEntity {
  id: number;
  messages: MessageEntity[];
  status: 'CLOSED' | 'OPEN'
}

// MessageEntity
class MessageEntity{
  id: number;
  status: 'DRAFT' | 'WAITING' | 'SENT'
}

// Allow if campaign has no messages
can(Close, CampaignEntity, {
  messages: { $size: 0 },
});

// Allow if every message status is SENT
can(Close, CampaignEntity, {
  messages: { /* all messages have status === 'SENT' */ },
});

If $not had been a valid operator, I would have used this:

can(Close, CampaignEntity, {
  messages: {
    $not: { $elemMatch: { status: { $ne: 'SENT' } } },
  },
});
Share Improve this question edited Jan 20 at 8:05 DarkBee 15.7k8 gold badges70 silver badges114 bronze badges asked Jan 20 at 8:05 MartialMartial 1,56215 silver badges27 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You have few options:

  1. Add $not operator and use custom conditions matcher - https://casl.js.org/v6/en/advanced/customize-ability#extend-conditions-with-custom-operators
  2. use combination of can and cannot. Allow to close campaigns but not those which has messages with status different from SENT
can(Close, CampaignEntity)
cannot(Close, CampaignEntity, {
  messages: { 
    $elemMatch: { 
      status: { $ne: SENT } 
    }      
  }
})
发布评论

评论列表(0)

  1. 暂无评论