guardContent function
Implementation
String guardContent(
ServerLifecycleComponent component,
String Function(Spec) formatter,
) {
final (:positioned, :named) = getParams(
component.params,
defaultExpression: createGetFromDi(),
);
final clazz = Class(
(p) => p
..name = component.guardClass.className
..implements.add(refer((Guard).name))
..constructors.add(
Constructor(
(p) => p
..constant = true
..requiredParameters.add(
Parameter(
(p) => p
..name = 'di'
..toThis = true
..named = false,
),
),
),
)
..fields.add(
Field(
(p) => p
..type = refer('DI')
..name = 'di'
..modifier = FieldModifier.final$,
),
)
..methods.add(
Method(
(p) => p
..name = 'protect'
..returns = refer('Future<${(GuardResult).name}>')
..modifier = MethodModifier.async
..annotations.add(refer('override'))
..requiredParameters.add(
Parameter(
(p) => p
..name = 'context'
..type = refer((GuardContext).name),
),
)
..body = Block.of(
[
declareFinal('component')
.assign(
refer(component.name).newInstance(positioned, named),
)
.statement,
const Code('\n'),
declareFinal('guards')
.assign(
literalList(
[
...createComponentMethods(
component.guards,
inferredParams: {
(GuardContext).name: refer('context'),
(GuardMeta).name:
refer('context').property('meta'),
},
),
],
refer('FutureOr<${(GuardResult).name}> Function()'),
),
)
.statement,
const Code('\n'),
forInLoop(
declaration: declareFinal('guard'),
iterable: refer('guards'),
body: Block.of([
declareFinal('result')
.assign(
switchPatternStatement(
refer('guard').call([]),
cases: [
(
declareFinal(
'future',
type: refer('Future<${(GuardResult).name}>'),
).code,
refer('future').code,
),
(
declareFinal(
'result',
type: refer((GuardResult).name),
).code,
refer('Future')
.property('value')
.call([refer('result')]).code,
),
],
).awaited,
)
.statement,
const Code('\n'),
ifStatement(
refer('result').property('isBlock'),
body: refer('result').returned.statement,
).code,
]),
).code,
const Code('\n'),
declareConst((GuardResult).name)
.property('pass')
.call([])
.returned
.statement,
],
),
),
),
);
return formatter(clazz);
}