65 lines
1.8 KiB
C#
65 lines
1.8 KiB
C#
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
using System.Threading.Tasks;
|
|
using CPATapi.Server.Models;
|
|
using Dapper;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Data.SqlClient;
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
namespace CPATapi.Server.Controllers
|
|
{
|
|
[Route("[controller]")]
|
|
[ApiController]
|
|
public class SearchController : ControllerBase
|
|
{
|
|
private readonly IConfiguration _config;
|
|
public SearchController(IConfiguration config) => _config = config;
|
|
|
|
[HttpGet]
|
|
public async Task<IEnumerable<TapiContact>> SearchAsync([FromQuery] string query)
|
|
{
|
|
if (query == null)
|
|
{
|
|
return new List<TapiContact>();
|
|
}
|
|
|
|
var args = Regex.Split(query, "\\s").Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()).ToArray();
|
|
|
|
if (args.Length == 0)
|
|
{
|
|
return new List<TapiContact>();
|
|
}
|
|
|
|
await using var con = new SqlConnection(_config["Db:ConnectionString"]);
|
|
await con.OpenAsync();
|
|
var sql = new StringBuilder(@"
|
|
SELECT TOP 10
|
|
TD_ID,
|
|
TD_NAME,
|
|
TD_NUMBER,
|
|
TD_NUMBER_TAPI,
|
|
TD_MEDIUM
|
|
FROM dbo.CP_TAPI_DIRECTORY
|
|
WHERE ");
|
|
var first = true;
|
|
var dp = new DynamicParameters();
|
|
for (var i = 1; i <= args.Length; i++)
|
|
{
|
|
if (!first)
|
|
{
|
|
sql.AppendLine("AND");
|
|
}
|
|
first = false;
|
|
sql.AppendLine($"(TD_NAME LIKE @s{i} OR");
|
|
sql.AppendLine($" TD_NUMBER_TAPI LIKE @s{i})");
|
|
dp.Add($"s{i}", $"%{args[i-1]}%");
|
|
}
|
|
|
|
return await con.QueryAsync<TapiContact>(sql.ToString(), dp);
|
|
}
|
|
}
|
|
}
|