public async Task <CreateNewShortUrlCommandResponse> Handle(CreateNewShortUrlCommand request, CancellationToken cancellationToken) { var slug = request.ShortUrl.Slug; if (!string.IsNullOrEmpty(slug)) { var url = await _repository.Get(slug); if (url != null) { return(new CreateNewShortUrlCommandResponse() { IsConflict = true, ConflictMessage = $"Slug '{url.Slug}' is in use" }); } } if (string.IsNullOrEmpty(slug)) { var xeger = new Xeger("[a-z0-9]{5}", new Random()); slug = xeger.Generate(); } request.ShortUrl.Slug = slug.ToLower(); var res = await _repository.Create(request.ShortUrl); return(new CreateNewShortUrlCommandResponse() { ShortUrl = res }); }
/// <summary> /// create new short url /// </summary> /// <param name="model">most important thing is in the model is the ActualURL</param> /// <returns></returns> public ShortUrlResponseModel Create(ShortURLRequestModel model) { //check if the url saved perviously ShortURLModel foundUrl = URLExist(model.ActualURL); if (foundUrl != null) { return(new ShortUrlResponseModel { Model = foundUrl, Success = false, Message = "This url has been saved befor" }); } //create new model to save in data base ShortURLModel shortURLModel = new ShortURLModel { DateOfCreation = DateTime.Now, ActualURL = model.ActualURL, //try to create a random alphanumeric short url ShortenedURL = AutoURLGenerator.ShortUrlGenerator(8) }; //save the model to database var result = _shortUrlRepository.Create(shortURLModel); //return the result return(new ShortUrlResponseModel { Model = result, Success = true, Message = "Saved successfully" }); }
public async Task <IActionResult> Create([FromBody] ShortUrlCreateDto shortUrlDto) { var shortUrl = _mapper.Map <ShortUrl>(shortUrlDto); shortUrl.Url = _nanoIdGenerator.Generate(); shortUrl.ApiKeyId = 1; shortUrl.isPermanent = false; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var success = await _shortUrlRepository.Create(shortUrl); if (!success) { return(BadRequest()); } var response = _mapper.Map <ShortUrlDto>(shortUrl); return(Created("Create", new { response })); }