Использование Laravel Echo (Pusher) на Laravel Vapor - PullRequest
0 голосов
/ 06 апреля 2020

У меня были некоторые трудности с выяснением, почему мои события не «запускаются» во внешнем интерфейсе (Laravel Echo + Pusher), когда мое приложение разворачивается через Laravel Vapor, даже если оно отлично работает локально.

Консоль отладки Pushers фактически показывала, что события на самом деле отправляются в Pusher приложением Laravel.

Так как я потратил около полдня, чтобы выяснить, что был не прав (к счастью, я увидел, что мое сообщение отображается в реальном времени в моей локальной среде вместо постановки после публикации чего-либо о постановке), хотя я потрачу еще 10 минут, чтобы написать здесь сообщение, поэтому некоторые люди (надеюсь) не не нужно тратить столько времени.

Ответы [ 2 ]

1 голос
/ 18 апреля 2020

Я потратил часов , пытаясь выяснить ту же проблему, и собирался ее потерять.

Я только что обнаружил эту публикацию, описывающую пакет npm, который помогает с этим.

Источник https://codinglabs.com.au/blog/2019/8/using-environment-specific-variables-in-laravel-vapor-with-mix

NPM пакет https://laravel-mix.com/extensions/env-file

0 голосов
/ 06 апреля 2020

На самом деле проблема заключалась в следующем:

  • Vapor сначала строит приложение локально в каталоге .vapor.
  • Ключ PUSHER из .env, загруженный во время этой сборки Процесс в вашей локальной .env (!) означает, что он ничего не изменит, если вы установите переменные окружения MIX_PUSHER_APP_KEY и MIX_PUSHER_APP_CLUSTER в вашей .env.{environment} (которую вы получили при запуске vapor env:pull {environment}.

Я решил это быстро (и грязно):

  • Добавьте еще несколько переменных среды:
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=eu

# Necessary in `php artisan pusher:credentials`
PUSHER_LOCAL_APP_KEY=
PUSHER_LOCAL_APP_CLUSTER=eu

# Necessary in `php artisan pusher:credentials`
PUSHER_STAGING_APP_KEY=
PUSHER_STAGING_APP_CLUSTER=eu

# Necessary in `php artisan pusher:credentials`
PUSHER_PRODUCTION_APP_KEY=
PUSHER_PRODUCTION_APP_CLUSTER=eu

MIX_PUSHER_APP_KEY="${PUSHER_LOCAL_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_LOCAL_APP_CLUSTER}"
  • Добавление новой команды (до yarn run production) в процесс сборки Vapor: php artisan pusher:credentials {environment}. Поэтому для постановки вы должны использовать php artisan pusher:credentials staging.

Команда выглядит следующим образом:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
use Illuminate\Support\Str;

final class SwapPusherCredentials extends Command
{
    use ConfirmableTrait;

    private array $keyPatterns = [
        'PUSHER_%sAPP_KEY',
        'PUSHER_%sAPP_CLUSTER',
    ];

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pusher:credentials {environment=production}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sets the pusher credentials based on the current environment';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @throws \Exception
     */
    public function handle()
    {
        // Basically we're fixing a bug (?) in Vapor. Since we're building the front end locally,
        // we need to swap the pusher keys before building. If we don't do this, the front end
        // will be built with local pusher keys. When posting messages not local it's broken
        $environment = Str::upper($this->argument('environment'));

        $this->updatePusherEnvironmentVariables($environment);
    }

    /**
     * @param string $environment
     * @throws \Exception
     */
    private function updatePusherEnvironmentVariables(string $environment)
    {
        foreach ($this->keyPatterns as $pattern) {
            // 'PUSHER_LOCAL_APP_KEY' || 'PUSHER_STAGING_APP_KEY' etc.
            $variableToSet = sprintf($pattern, $environment . '_');

            // 'PUSHER_APP_KEY'
            $targetVariableName = sprintf($pattern, '');

            if (!env($targetVariableName, false)) {
                throw new \Exception('Missing environment value for ' . $targetVariableName);
            }

            $this->setVariable($targetVariableName, $variableToSet);
        }
    }

    private function setVariable(string $targetVariableName, string $variableToSet)
    {
        file_put_contents($this->laravel->environmentFilePath(), preg_replace(
            $this->replacementPattern($targetVariableName),
            $replacement = '${' . $variableToSet . '}',
            file_get_contents($this->laravel->environmentFilePath())
        ));

        $this->info("Successfully set MIX_{$targetVariableName} to {$replacement}!");
    }

    private function replacementPattern(string $targetVariableName)
    {
        // Don't remove notsurebutfixes, when removed it doesn't match the first entry
        // So it will match all keys except PUSHER_LOCAL_* for some reason.
        $escaped = '\=notsurebutfixes|\$\{' . $this->insertEnvironmentIntoKey('LOCAL',
                $targetVariableName) . '\}|\$\{' . $this->insertEnvironmentIntoKey('STAGING',
                $targetVariableName) . '\}|\$\{' . $this->insertEnvironmentIntoKey('PRODUCTION',
                $targetVariableName) . '\}';

        return "/^MIX_$targetVariableName{$escaped}/m";
    }

    // Insert the environment after PUSHER_ in any PUSHER_* like variable passed in.
    // So basically PUSHER_APP_KEY => PUSHER_LOCAL_APP_KEY
    private function insertEnvironmentIntoKey($environment, $key)
    {
        $parts = explode('_', $key, 2);

        return $parts[0] . '_' . $environment . '_' . $parts[1];
    }
}

Вот и все. Теперь файл .env в каталоге .vapor будет обновляться во время развертывания для использования PUSHER_STAGING_APP_KEY и PUSHER_STAGING_APP_CLUSTER!

...