Ejemplo n.º 1
0
        public async Task <ServiceResult <string> > CreateShortCode(SourceUrlDto entity)
        {
            var result = new ServiceResult <string>();

            try
            {
                Boolean isValid = true;
                try
                {
                    entity.Url.ValidateUrl();
                }
                catch (Exception)
                {
                    result.AddError("", "Invalid Url");
                    isValid = false;
                }

                if (isValid)
                {
                    var codeResult = await this.GenerateShortCode(entity);

                    result.Response = codeResult.Code.ToString();
                }

                return(result);
            }
            catch (Exception e)
            {
                result.AddError("", e.InnerException.ToString());
            }

            return(result);
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Create(SourceUrlDto model)
        {
            try
            {
                var result = await _urlService.CreateShortCode(model);

                if (!result.IsSuccess)
                {
                    return(BadRequest(result));
                }

                return(Ok(result.Response));
            }
            catch (Exception ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Ejemplo n.º 3
0
        private async Task <Url> GenerateShortCode(SourceUrlDto sourceUrl)
        {
            var existing = await this.IsAlreadyShortened(sourceUrl.Url);

            if (existing != null)
            {
                return(existing);
            }
            else
            {
                var code = await this.GetCode(sourceUrl);

                var shortCode = new Url {
                    Id = Guid.NewGuid().ToString(), SourceUrl = sourceUrl.Url, Start_Date = DateTime.UtcNow, Code = code
                };

                DB.Urls.Add(shortCode);
                await DB.SaveChangesAsync();

                return(shortCode);
            }
        }
Ejemplo n.º 4
0
        protected async Task <string> GetCode(SourceUrlDto sourceUrl)
        {
            var code     = "";
            var existing = await DB.Urls.SingleOrDefaultAsync(x => x.SourceUrl == sourceUrl.Url);

            if (existing == null)
            {
                if (sourceUrl.Code == "")
                {
                    code = ShortCodeGenerator.Generate();
                }
                else
                {
                    code = sourceUrl.Code;
                }
            }
            else
            {
                code = existing.Code;
            }
            return(code);
        }