Example #1
0
        static async Task <string?> ApplyTemplateAsync(
            EntityTemplate template,
            EntityTemplateFunctions functions,
            TemplateImportState state,
            SeqConnection connection,
            RootEntity apiRoot,
            bool merge)
        {
            if (!JsonTemplateEvaluator.TryEvaluate(template.Entity, functions.Exports, out var entity, out var error))
            {
                return(error);
            }

            var asObject = (IDictionary <string, object>)JsonTemplateObjectGraphConverter.Convert(entity);

            // O(Ntemplates) - easy target for optimization with some caching.
            var resourceGroupLink = template.ResourceGroup + "Resources";
            var link          = apiRoot.Links.Single(l => resourceGroupLink.Equals(l.Key, StringComparison.OrdinalIgnoreCase));
            var resourceGroup = await connection.Client.GetAsync <ResourceGroup>(apiRoot, link.Key);

            if (state.TryGetCreatedEntityId(template.Name, out var existingId) &&
                await CheckEntityExistenceAsync(connection, resourceGroup, existingId))
            {
                asObject["Id"] = existingId;
                await UpdateEntityAsync(connection, resourceGroup, asObject, existingId);

                Log.Information("Updated existing entity {EntityId} from {TemplateName}", existingId, template.Name);
            }
            else if (merge && !state.TryGetCreatedEntityId(template.Name, out _) &&
                     await TryFindMergeTargetAsync(connection, resourceGroup, asObject) is { } mergedId)
            {
                asObject["Id"] = mergedId;
                await UpdateEntityAsync(connection, resourceGroup, asObject, mergedId);

                state.AddOrUpdateCreatedEntityId(template.Name, mergedId);
                Log.Information("Merged and updated existing entity {EntityId} from {TemplateName}", existingId, template.Name);
            }