LastDragon-ru / lara-asp

Awesome Set of Packages for Laravel
MIT License
11 stars 1 forks source link

DateTime operators directives based on SQL functions like YEAR, MONTH, DAY. #138

Closed webard closed 7 months ago

webard commented 7 months ago

Thank you for next version of that great package.

In my project i'm using custom directives like @equalDay, @equalMonth, @equalYear, @equalHour etc. for datetime fields.

Code of directive looks like this:

<?php

declare(strict_types=1);

namespace App\GraphQL\Directives;

use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use LastDragon_ru\LaraASP\GraphQL\Builder\Contracts\Context;
use LastDragon_ru\LaraASP\GraphQL\Builder\Contracts\Handler;
use LastDragon_ru\LaraASP\GraphQL\Builder\Exceptions\OperatorUnsupportedBuilder;
use LastDragon_ru\LaraASP\GraphQL\Builder\Field;
use LastDragon_ru\LaraASP\GraphQL\Builder\Traits\WithScoutSupport;
use LastDragon_ru\LaraASP\GraphQL\SearchBy\Operators\Operator;
use Nuwave\Lighthouse\Execution\Arguments\Argument;
use Override;

class SearchByOperatorEqualMonthDirective extends Operator
{
    use WithScoutSupport;

    public static function getName(): string
    {
        return 'equalMonth';
    }

    public function getFieldDescription(): string
    {
        return 'Equal month (`=`).';
    }

    #[Override]
    public function call(
        Handler $handler,
        object $builder,
        Field $field,
        Argument $argument,
        Context $context,
    ): object {
        $field = $this->resolver->getField($builder, $field->getParent());
        $value = $argument->toPlain();

        if ($builder instanceof EloquentBuilder || $builder instanceof QueryBuilder) {
            $builder->whereRaw((string) 'MONTH('.$field.')='.$value);
        } else {
            throw new OperatorUnsupportedBuilder($this, $builder);
        }

        return $builder;
    }
}

What do you think about including date operators directly in package, using SQL functions like YEAR, MONTH etc.?

LastDragon-ru commented 7 months ago

What do you think about including date operators directly in package, using SQL functions like YEAR, MONTH etc.?

I think they are too simple from one side (= can be implemented/added for less than a minute or two), and too complicated from another. I'm not sure how functions work in different DBs and, more important, the general implementation will require getting a timezone where is the user who makes a query to get a proper date (that will require some new interface, documentation, etc). So I'm not ready to include/implement it now. Sorry.

PS: use WithScoutSupport not needed.

webard commented 7 months ago

Ok, it is understandable. Thank you for response.