Welcome Guest, Not a member yet? Register   Sign In
error Middleware(filter) ci4
#1

(This post was last modified: 09-01-2021, 06:49 AM by paliz.)

here s my question i know express.js very well i wanna error middleware(filter) for ci4  to handdle   when it  throw excpection in service ci4 
compare ci4 and express.js 
look my code in express.js 
express controller 
Code:
import {NextFunction, Request, Response} from 'express';
import {StatusCodes} from 'http-status-codes';
import {default as i18n} from "i18next";
import ApiController from "./../../shared/controllers/api.controller";
import {RequestWithUser} from "../../auth/interfaces/reqeust.with.user.interface";
import ProfileService from "../services/profile.service";
import {UserEntity} from "../entities/user.entity";
import {IUser} from '../../auth/interfaces/user.interface';
class ProfileController extends ApiController {
  public profileService = new ProfileService();


  public index = async (req: RequestWithUser, res: Response, next: NextFunction) => {
    try {
      const user: IUser = req.user;
      const findOneData: IUser = await this.profileService.show(user._id);
      res.status(StatusCodes.OK).json({
        'statusMessage': i18n.t('api.commons.receive'),
        data: findOneData
      });
    } catch (error) {
      next(error);
    }
  };


  public create = async (req: RequestWithUser, res: Response, next: NextFunction) => {
    try {
      const user: IUser = req.user;
      const userEntity = new UserEntity(req.body);
      await userEntity.updateNow().generatePasswordHash();
      const updateData: IUser = await this.profileService.update(user._id, userEntity);
      res.status(StatusCodes.CREATED).json({
        'statusMessage': i18n.t('api.commons.save'),
        data: updateData
      });
    } catch (error) {
      next(error);
    }
  };


}

export default ProfileController;
express.js service 

Code:
import {HttpException} from '../../../app/exceptions/HttpException';
import {isEmpty} from '../../../app/utils/util';
import {StatusCodes} from "http-status-codes";
import {default as i18n} from "i18next";
import {UserEntity} from "../entities/user.entity";
import UserModel from "../../auth/models/user.model";
import {IUser} from "../../auth/interfaces/user.interface";
import { ServiceInterface } from "./../../shared/interfaces/service.interface";

class ProfileService  implements  ServiceInterface {
  public userModel = UserModel;


  public async show(id: string): Promise<IUser> {

    const findUser: IUser = await this.userModel.findOne({_id: id});
    if (!findUser) throw new HttpException(StatusCodes.CONFLICT, i18n.t('api.commons.exist'));

    return findUser;
  }


  public async update(id: string, profile: UserEntity): Promise<IUser> {
    if (isEmpty(profile)) throw new HttpException(StatusCodes.BAD_REQUEST, i18n.t('api.commons.validation'));



    const updateUserById: IUser = await this.userModel.findByIdAndUpdate(id, profile);
    if (!updateUserById) throw new HttpException(StatusCodes.CONFLICT, i18n.t('api.commons.reject'));

    return updateUserById;
  }

}

export default ProfileService;



express.js middleware(filter)

Code:
import { NextFunction, Request, Response } from 'express';
import { HttpException } from '../exceptions/HttpException';
import { logger } from '../utils/logger';

const errorMiddleware = (error: HttpException, req: Request, res: Response, next: NextFunction) => {
  try {
    const status: number = error.status || 500;
    const message: string = error.message || 'Something went wrong';

    logger.error(`[${req.method}] ${req.path} >> StatusCode:: ${status}, Message:: ${message}`);
    res.status(status).json({ message });
  } catch (error) {
    next(error);
  }
};

export default errorMiddleware;

code for ci4 

ci4 controller 
Code:
<?php namespace Modules\Common\Controllers;


use Modules\Common\Config\Services;


use CodeIgniter\HTTP\ResponseInterface;
use Modules\Shared\Controllers\ApiController;


class Profile extends ApiController
{

    /**
    * index function
    * @method : GET
    * @throws \Exception
    */
    public function index()
    {

        $profileService = Services::profileService();
        $profileService->setUserId( $this->userObject->id);
        $result = $profileService->index($this->urlQueryParam);
        return $this->respond([
            'data' => $result
        ], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
    }


    public function create()
    {


        $customConfig = new \Modules\Common\Config\ModuleCommonConfig();
        $imageService = \CodeIgniter\Config\Services::image();


        $rules = [
            'firstName' => 'if_exist|required|max_length[255]',
            'lastName' => 'if_exist|required|max_length[255]',
            'address' => 'if_exist|required|max_length[255]',
            'phone' => 'if_exist|required|max_length[11]',
            'password' => 'if_exist|required',
            'passConfirm' => 'if_exist|required|matches[password]',
            'gender' => 'if_exist|required',
            'country' => 'if_exist|required|max_length[255]',
            'city' => 'if_exist|required|max_length[255]',
            'image' => 'if_exist|uploaded[image]|max_size[image,4096]|ext_in[avatar,png,jpg,jpeg,webp]',

        ];

        if (!$this->validate($rules)) {

            return $this->respond([
                'error' => $this->validator->getErrors(),
                'success' => false
            ], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));

        }

        $userEntity = new \Myth\Auth\Entities\User($this->request->getBody());

        if (isset($_FILES['image'])) {


            $avatar = $this->request->getFile('image');
            $avatar->move($customConfig->profileDirectory, time() . '.' . $avatar->getClientExtension());
            $userEntity->image = $avatar->getName();
            $userEntity->editImage();
            $imageService->withFile(ROOTPATH . $userEntity->image)
                ->withResource()->fit(100, 100, 'center')
                ->save(ROOTPATH . $userEntity->image, 90);
        }

        $profileService = Services::profileService();
        $profileService->update($ $this->userObject->id, $userEntity);


        return $this->respond([
            'success' => true,

        ], ResponseInterface::HTTP_CREATED, lang('Shared.api.save'));

    }


}


ci4 service 

Code:
<?php namespace Modules\Common\Services;


use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Common\Libraries\CustomFile;
use Modules\Shared\Interfaces\UrlQueryParamInterface;

class  ProfileService
{
    private \Myth\Auth\Models\UserModel $model;
    private CustomFile $cfs;
    private string $userId;

    public function __construct()
    {
        $this->userId = "";
        $this->model = new  \Myth\Auth\Models\UserModel();
        $this->cfs = new CustomFile();
    }

    public function setUserId(string $userId): void
    {
        $this->userId = $userId;
    }

    /**
    * index function
    * @method : GET
    * @param UrlQueryParamInterface $urlQueryParam
    * @return array
    */
    public function index(UrlQueryParamInterface $urlQueryParam)
    {
        $result = $this->model->select('
        users.id,
      users.email,
      users.username,
      users.first_name,
      users.last_name,
      users.image,
      users.gender,
      users.birthday,
      users.country,
      users.city,
      users.address,
      users.phone,
      users.status_message,
      users.status,
      users.active,
      users.created_at,
      users.updated_at,
      users.deleted_at
        ')->find($this->userId);

        $data = ['data' => $result];
        return $data;
    }

    /**
    * update function
    * @method : Post
    * @param $id
    * @param \Myth\Auth\Entities\User $entity
    * @throws \ReflectionException
    */
    public function update($id, \Myth\Auth\Entities\User $entity)
    {
        if (is_null($entity)) throw new HttpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);


        $isExist = $this->model->where('id', $id)->first();

        if (is_null($isExist)) throw new HttpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);
        if ($isExist->image != 'public/upload/profile/default-avatar.jpg') {
            $this->cfs->removeSingleFile(ROOTPATH . $isExist->image);
        }




        if (!$this->model->update($id, $entity)) {
            helper('shared');
            $message = lang('Shared.api.reject') ." \n " . serializeMessages($this->model->errors());
            throw new HttpException($message, ResponseInterface::HTTP_BAD_REQUEST);

        }



    }


}

express.js handdle errors in middle ware but ci4 middleware dose not support this thing
and i dont wanna use response in service or i wanna be just like express.js
i wanna be like express.js what should i do

ci4 middleware it should be like that 


PHP Code:
<?php namespace Modules\Common\Filters;


use 
CodeIgniter\Filters\ExceptionFilterInterface;
use 
CodeIgniter\HTTP\Exceptions\HTTPException;
use 
Modules\Shared\Enums\FilterErrorType;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use  CodeIgniter\Config\Services;


class 
ExceptionFilter implements ExceptionFilterInterface
{
    public function after(HTTPException $errorRequestInterface $requestResponseInterface $response$arguments null)
    {

          try {

          } catch (\Exception $error) {
        if ($error->getMessage())
            return Services::response()->setJSON(['success' => false,
                'type' => FilterErrorType::Error,
                'error' => $error->getMessage(),
                'trace' => $error->getTraceAsString()
            ])->setContentType('application/json')
                ->setStatusCode($error->getCode(), lang('Authenticate.filter.error'));

        }

    }

    public function before(HTTPException $errorRequestInterface $request$arguments null)
    {


    }




PHP Code:
<?php

/**
 * This file is part of the CodeIgniter 4 framework.
 *
 * (c) CodeIgniter Foundation <[email protected]>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CodeIgniter\Filters;

use 
CodeIgniter\Exceptions\ExceptionInterface;
use 
CodeIgniter\HTTP\Exceptions\HTTPException;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;

/**
 * Filter interface
 */
interface ExceptionFilterInterface
{
    /**
    * Do whatever processing this filter needs to do.
    * By default it should not return anything during
    * normal execution. However, when an abnormal state
    * is found, it should return an instance of
    * CodeIgniter\HTTP\Response. If it does, script
    * execution will end and that Response will be
    * sent back to the client, allowing for error pages,
    * redirects, etc.
    *
    * @param ExceptionInterface $error
    * @param RequestInterface $request
    * @param null $arguments
    *
    * @return mixed
    */
    public function before(HTTPException $errorRequestInterface $request$arguments null);

    //--------------------------------------------------------------------

    /**
    * Allows After filters to inspect and modify the response
    * object as needed. This method does not allow any way
    * to stop execution of other after filters, short of
    * throwing an Exception or Error.
    *
    * @param ExceptionInterface $error
    * @param RequestInterface $request
    * @param ResponseInterface $response
    * @param null $arguments
    *
    * @return mixed
    */
    public function after(HTTPException $error,RequestInterface $requestResponseInterface $response$arguments null);

    //--------------------------------------------------------------------

Enlightenment  Is  Freedom
Reply
#2

since ci4 dose accept express.js approach  so 
i created class MainService   other service extend from it 
and define function to stop  execution show custom reponse with native  php  
PHP Code:
<?php

namespace Modules\Shared\Libraries;
use 
CodeIgniter\HTTP\Exceptions\HTTPException;

class 
MainMainService  
{

    protected function responseHttpExceptionstring $messageint $code,?string $body null)
    {

        try {

            throw new HttpException($message$code);

        } catch (\Exception $e) {
            header("HTTP/1.1 {$code} {$message}");
            $json json_encode(['error' => $body]);
            echo $json;
        }

        exit();
    }








PHP Code:
<?php namespace Modules\Common\Services;


use 
CodeIgniter\HTTP\Exceptions\HTTPException;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Modules\Common\Libraries\CustomFile;
use 
Modules\Shared\Interfaces\UrlQueryParamInterface;
use 
Modules\Shared\Libraries\MainMainService;

class  ProfileService extends MainMainService
{
    private \Myth\Auth\Models\UserModel $model;
    private CustomFile $cfs;
    private string $userId;

    public function __construct()
    {
        $this->userId "";
        $this->model new  \Myth\Auth\Models\UserModel();
        $this->cfs = new CustomFile();
    }

    public function setUserId(string $userId): void
    
{
        $this->userId $userId;
    }

    /**
    * index function
    * @method : GET
    * @param UrlQueryParamInterface $urlQueryParam
    * @return array
    */
    public function index(UrlQueryParamInterface $urlQueryParam)
    {
        $result $this->model->select('
        users.id,
      users.email,
      users.username,
      users.first_name,
      users.last_name,
      users.image,
      users.gender,
      users.birthday,
      users.country,
      users.city,
      users.address,
      users.phone,
      users.status_message,
      users.status,
      users.active,
      users.created_at,
      users.updated_at,
      users.deleted_at
        '
)->find($this->userId);

        $data = ['data' => $result];
        return $data;
    }

    /**
    * update function
    * @method : Post
    * @param $id
    * @param \Myth\Auth\Entities\User $entity
    * @throws \ReflectionException
    */
    public function update($id, \Myth\Auth\Entities\User $entity)
    {

        if (is_null($entity)) $this->responseHttpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);


        $isExist $this->model->where('id'$id)->first();

        if (is_null($isExist)) $this->responseHttpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);
        if ($isExist->image != 'public/upload/profile/default-avatar.jpg') {
            $this->cfs->removeSingleFile(ROOTPATH $isExist->image);
        }


        if (!$this->model->update($id$entity)) {
            helper('shared');
            $message lang('Shared.api.reject');
            $this->responseHttpException($messageResponseInterface::HTTP_BAD_REQUESTserializeMessages($this->model->errors()));

        }


    }



Enlightenment  Is  Freedom
Reply




Theme © iAndrew 2016 - Forum software by © MyBB