0

I'm trying to simulate the behavior of firebases rules with node, where I create an object with the routes ad the handlers per each route, but I'm getting problems with the typescript interface, here is what I have:

interface Rule {
    allowReadIf?: () => boolean,
    allowWriteIf?: () => boolean,
    allowAllIf?: () => boolean,
    routes?: {
        [key: string]: Rule
    }
}

But I don't like the routes key, because any child route would have another routes and that's useless... I'd like something more like:

interface Rule {
    allowReadIf?: () => boolean,
    allowWriteIf?: () => boolean,
    allowAllIf?: () => boolean,
    [key: string]: Rule // This creates me errors, because allowReadIf, allowWriteIf... can't be assigned to type Rule
}

So I could use in this way:

'clients': {
    allowAllIf: () => isLogged(),
    'details': {
        ...
    },
    'add': {
        allowWriteIf: () => isAdmin()
    }
}

Instead of creating a routes key per each child, this would be uggly with many nested routes

 'clients': {
        allowAllIf: () => isLogged(),
        routes: {
            'details': {
                ...
            },
            'add': {
                allowWriteIf: () => isAdmin()
            }
        }
    }

In this case I would have a route /clients that will only handle requests from logged users, all users can access the details... but only admins can call /clients/add

In simple words, instead of having:

myVar['clients']['routes']['details']

I want to have:

myVar['clients']['details']
Leo Letto
  • 1,774
  • 1
  • 12
  • 17
  • Not sure I understand. You don't like a separate`routes` object because you have only 1-level depth? – tokland Jun 29 '20 at 18:01
  • Hey @tokland just added another example to the question, hope it will help you to understand better my question – Leo Letto Jun 29 '20 at 18:07
  • 1
    I see, you have arbitrarily nested routes. I think your first approach is perfectly fine, I see no reason to flatten that structure, you'll mix things up. In any case, this addresses your question, use `type` with an intersection: https://stackoverflow.com/a/57774438/188031 In fact, I'd type everything, even the route keys, so the type system will help you a lot when working with the routing. – tokland Jun 29 '20 at 18:14
  • I read this link, and in his example, he has only 1-level depth, and it doesn't work if do something like `p.other.other`, thank you for your advice, but I would like to keep things in same lavel instead of creating another key just for the routes, could you make an example if it is possible? – Leo Letto Jun 29 '20 at 18:29
  • What if you want a route at `clients/allowAllIf`? – Alex Wayne Jun 29 '20 at 22:42
  • Well i couldn't use it, or in that case I would have to search for better names for these methods which is not my case at the moment – Leo Letto Jun 29 '20 at 22:47

0 Answers0