Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FEAT: Implemented an endpoint to search for jobs by company name. #435

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,12 @@ BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
DesignTimeDbContextFactory.cs
artifacts/

# Rider generated
.idea/

# ASP.NET Scaffolding
ScaffoldingReadMe.txt

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using AutoMapper;
using Hng.Application.Features.Jobs.Dtos;
using Hng.Application.Features.Jobs.Handlers;
using Hng.Application.Features.Jobs.Queries;
using Hng.Domain.Entities;
using Hng.Infrastructure.Repository.Interface;
using Microsoft.AspNetCore.Http;
using Moq;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace Hng.Application.Test.Features.Job
{
public class GetJobsByCompanyNameQueryShould
{
private readonly Mock<IRepository<Domain.Entities.Job>> _mockRepository;
private readonly IMapper _mapper;
private readonly GetJobsByCompanyNameQueryHandler _handler;

public GetJobsByCompanyNameQueryShould()
{
_mockRepository = new Mock<IRepository<Domain.Entities.Job>>();

var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Domain.Entities.Job, JobDto>();
});
_mapper = config.CreateMapper();

_handler = new GetJobsByCompanyNameQueryHandler(_mockRepository.Object, _mapper);
}

[Fact]
public async Task ReturnOnlyJobsForCompany_WhenCompanyNameIsProvided()
{
// Arrange
var jobs = new List<Domain.Entities.Job>
{
new Domain.Entities.Job { Id = Guid.NewGuid(), Title = "Software Engineer", Company = "TechCorp" },
new Domain.Entities.Job { Id = Guid.NewGuid(), Title = "Frontend Developer", Company = "TechCorp" },
new Domain.Entities.Job { Id = Guid.NewGuid(), Title = "Backend Developer", Company = "OtherCorp" }
};

_mockRepository.Setup(repo => repo.GetAllAsync()).ReturnsAsync(jobs);

var query = new GetJobsByCompanyNameQuery("TechCorp");

// Act
var result = await _handler.Handle(query, CancellationToken.None);

// Assert
Assert.Equal(StatusCodes.Status200OK, result.StatusCode);
Assert.True(result.Success);
Assert.Equal("Jobs retrieved successfully.", result.Message);
Assert.Equal(2, result.Data.Count); // Only 2 jobs should match "TechCorp"
Assert.All(result.Data, job => Assert.Equal("TechCorp", job.Company)); // Ensure all jobs are from TechCorp
}

[Fact]
public async Task ReturnBadRequest_WhenCompanyNameIsEmpty()
{
// Arrange
var query = new GetJobsByCompanyNameQuery(""); // Empty company name

// Act
var result = await _handler.Handle(query, CancellationToken.None);

// Assert
Assert.Equal(StatusCodes.Status400BadRequest, result.StatusCode);
Assert.False(result.Success);
Assert.Equal("Company name must be provided.", result.Message);
Assert.Null(result.Data);
}

[Fact]
public async Task ReturnNotFound_WhenNoJobsExistForCompany()
{
// Arrange
var jobs = new List<Domain.Entities.Job>
{
new Domain.Entities.Job { Id = Guid.NewGuid(), Title = "Software Engineer", Company = "OtherCorp" }
};

_mockRepository.Setup(repo => repo.GetAllAsync()).ReturnsAsync(jobs);

var query = new GetJobsByCompanyNameQuery("NonExistentCorp");

// Act
var result = await _handler.Handle(query, CancellationToken.None);

// Assert
Assert.Equal(StatusCodes.Status404NotFound, result.StatusCode);
Assert.False(result.Success);
Assert.Equal("No jobs were found for the specified company.", result.Message);
Assert.Null(result.Data);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Hng.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace Hng.Application.Features.Jobs.Dtos
{
public class GetJobByCompanyNameResponseDto
{
[JsonPropertyName("status_code")]
public int StatusCode { get; set; }

[JsonPropertyName("message")]
public string Message { get; set; }

[JsonPropertyName("success")]
public bool Success { get; set; }

[JsonPropertyName("data")]
public List<JobDto> Data { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using AutoMapper;
using Hng.Application.Features.Jobs.Dtos;
using Hng.Application.Features.Jobs.Queries;
using Hng.Domain.Entities;
using Hng.Infrastructure.Repository.Interface;
using MediatR;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Hng.Application.Features.Jobs.Handlers
{
public class GetJobsByCompanyNameQueryHandler : IRequestHandler<GetJobsByCompanyNameQuery, GetJobByCompanyNameResponseDto>
{
private readonly IRepository<Job> _jobRepository;
private readonly IMapper _mapper;

public GetJobsByCompanyNameQueryHandler(IRepository<Job> jobRepository, IMapper mapper)
{
_jobRepository = jobRepository;
_mapper = mapper;
}

public async Task<GetJobByCompanyNameResponseDto> Handle(GetJobsByCompanyNameQuery request, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(request.CompanyName))
{
return new GetJobByCompanyNameResponseDto
{
StatusCode = StatusCodes.Status400BadRequest,
Message = "Company name must be provided.",
Success = false,
Data = null
};
}

var jobs = await _jobRepository.GetAllAsync() ?? new List<Job>();

jobs = jobs.Where(p => p.Company?.Equals(request.CompanyName, StringComparison.OrdinalIgnoreCase) ?? false)
.ToList();

if (!jobs.Any())
{
return new GetJobByCompanyNameResponseDto
{
StatusCode = StatusCodes.Status404NotFound,
Message = "No jobs were found for the specified company.",
Success = false,
Data = null
};
}

var mappedJobs = _mapper.Map<List<JobDto>>(jobs);

return new GetJobByCompanyNameResponseDto
{
StatusCode = StatusCodes.Status200OK,
Message = "Jobs retrieved successfully.",
Success = true,
Data = mappedJobs
};
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Hng.Application.Features.Jobs.Dtos;
using MediatR;

namespace Hng.Application.Features.Jobs.Queries;

public class GetJobsByCompanyNameQuery : IRequest<GetJobByCompanyNameResponseDto>
{
public string CompanyName { get; set; }

public GetJobsByCompanyNameQuery(string companyName)
{
CompanyName = companyName;
}
}
1 change: 0 additions & 1 deletion src/Hng.Application/Hng.Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
</ItemGroup>

<ItemGroup>
<Folder Include="Features\Jobs\Queries\" />
<Folder Include="Features\SuperAdmin\Commands\" />
<Folder Include="Features\Timezones\Handlers\Queries\" />
<Folder Include="Features\Timezones\Queries\" />
Expand Down
17 changes: 17 additions & 0 deletions src/Hng.Web/Controllers/JobController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,21 @@ public async Task<ActionResult> DeleteJobById(Guid id)
await _mediator.Send(new DeleteJobByIdCommand(id));
return NoContent();
}


/// <summary>
/// Job - Search jobs by company name
/// </summary>
[HttpGet("search/company-name")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]

public async Task<ActionResult<IEnumerable<JobDto>>> GetJobByCompanyName([FromQuery] string CompanyName)
{
var query = new GetJobsByCompanyNameQuery(CompanyName);
var jobs = await _mediator.Send(query);
return Ok(jobs);
}
}
11 changes: 6 additions & 5 deletions src/Hng.Web/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnectionString": "",
"RedisConnectionString": ""
"DefaultConnectionString": "Host=localhost; Port=5432; Database=boiler_plate_db; Username=postgres; Password=\"Test123$\";",
"RedisConnectionString": "localhost:6379"

},
"Jwt": {
"SecretKey": "",
"ExpireInMinute": ""
"SecretKey": "V@7y$#z9Gq!Np3X2rD6&K*B5wLm%+T8aJ4fH",
"ExpireInMinute": "15"
},
"PaystackApiKeys": {
"Endpoint": "https://api.paystack.co/",
Expand All @@ -21,7 +22,7 @@
},
"SmtpCredentials": {
"Host": "",
"Port": "",
"Port": 587,
"Username": "",
"Password": ""
},
Expand Down
Loading