Skip to content

Commit

Permalink
V4 Released
Browse files Browse the repository at this point in the history
  • Loading branch information
rmunate authored and rmunate committed Nov 17, 2023
1 parent 34fd320 commit f42d50b
Show file tree
Hide file tree
Showing 6 changed files with 161 additions and 26 deletions.
33 changes: 20 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,35 @@
# PHP2JS
# PHP2JS / QUICKREQUEST

## The Library that Made Handling Monoliths in Laravel Simple - LARAVEL PHP Framework
# 🚀 Seamless Integration: PHP2JS & QuickRequest 🚀

Share PHP Laravel values effortlessly with external JavaScript files using just one command, thanks to the seamless integration of PHP2JS. Execute backend requests swiftly and precisely with the power of QuickRequest.

⚙️ This library is compatible with Laravel versions 9.0 and above ⚙️
Developing Laravel monoliths has never been easier and more efficient! 💻✨

[![Laravel 9.0+](https://img.shields.io/badge/Laravel-9.0%2B-orange.svg)](https://laravel.com)
[![Laravel 10.0+](https://img.shields.io/badge/Laravel-10.0%2B-orange.svg)](https://laravel.com)
## The Library that Made Handling Monoliths in Laravel Simple - LARAVEL PHP Framework

![logo-php2js](https://github.com/alejandrodiazpinilla/PHP2JS/assets/51100789/f3c09be3-8013-44de-87fe-946b55f14514)
![LOGO-PHP2JS-QR](https://github.com/rmunate/PHP2JS/assets/91748598/9b1efced-bd6b-494a-8f70-8e77e0fd0a84)

## Documentation
[![📖📖📖 **FULL DOCUMENTATION** 📖📖📖](https://img.shields.io/badge/FULL%20DOCUMENTATION-Visit%20Here-blue?style=for-the-badge)](https://rmunate.github.io/PHP2JS/)

## Installation
To install the dependency via Composer, run the following command:
## Installation PHP2JS
To install the dependency via Composer.

```console
```shell
composer require rmunate/php2js
```

Make sure that in the `composer.json` file, you have the library in the latest version. `"rmunate/php2js": "^3.8"`
Always after installing, run the command:
```console
php artisan php2js:clear
## Installation QuickRequest
Installing **QuickRequest** in Laravel projects is a simple process. Include the following import statement in the HEAD section of your project:

```html
<head>
<!-- ... -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://cdn.jsdelivr.net/gh/rmunate/PHP2JS@4/src/JS/QuickRequest/QuickRequest.min.js"></script>
<!-- ... -->
</head>
```

## License
Expand Down
1 change: 1 addition & 0 deletions docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ export default defineConfig({
{text: 'Examples', link: '/v4/quick-request/examples'},
{text: 'Blobs', link: '/v4/quick-request/blobs'},
{text: 'Laravel Errors', link: '/v4/quick-request/laravel-errors'},
{text: 'Excepciones', link: '/v4/quick-request/excepciones'},
]
}, {
text: 'Contribute',
Expand Down
26 changes: 26 additions & 0 deletions docs/v4/quick-request/excepciones.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
title: Examples
outline: deep
---
# Exceptions:

In case there is an error in the structure or processing of the data with QuickRequest, you will see an exception in the browser console like the following:

```shell
QuickRequest.js:27 ⚠ QuickRequestException ⚠ | Error: Could not find any form with the id AnyForm
{
"name": "Error",
"message": "Could not find any form with the id AnyForm",
"trace": [
"Error: Could not find any form with the id AnyForm",
"🔍 At: new QuickRequestException (http://laravel.com/QuickRequest.js:24:23)",
"🔍 At: QuickRequestFetch.data (http://laravel.com/QuickRequest.js:489:23)",
"🔍 At: QuickRequestFetch.send (http://laravel.com/QuickRequest.js:659:14)",
"🔍 At: QuickRequestFetch.dispatch (http://laravel.com/QuickRequest.js:649:18)",
"🔍 At: new QuickRequestFetch (http://laravel.com/QuickRequest.js:466:14)",
"🔍 At: HTMLFormElement.funcEvent (http://laravel.com/QuickRequest.js:421:21)"
]
}
```

It will be very easy to identify the error that occurred, as well as view the error trace.
112 changes: 102 additions & 10 deletions docs/v4/quick-request/laravel-errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,124 @@ title: Laravel Errors
outline: deep
---

# Errores
# Errors

Ahora veremos como recibiremos los errores que sucedan en el tratameitno de nuestra solicitud por parte del backend de laravel. Ya sea por FormRequest, Validator, Exceptions o cualquier otro origen.
Now let's see how we can handle errors that occur during the processing of our request by the Laravel backend. Whether it's due to FormRequest, Validator, Exceptions, or any other source.

Es escencial recibir una respuesta estandar de los errores ocurridos, ya que no es común el crear personalizaciones por cada una de las peticiones al backend de los posibles errores generados.
It is essential to receive a standardized response for the errors that occur because it is not common to create customizations for each request to the backend for possible generated errors.

Para esto QuickRequest siempre retorna una misma estructura de errores, independientemente sean errores lanzados de forma proghramada en nuestro codigo, por bloques catch o por expeciones del Marco.
For this, QuickRequest always returns the same error structure, regardless of whether errors are thrown in our code, caught in catch blocks, or thrown as exceptions in the framework.

A continuacion vemos la estructura con la que llega el valor a la funcion `error`
Below is the structure that the value passed to the `error` function looks like:

```javascript
QuickRequest.get({
//...
error: function(err){

//Veamos la estrcutura:
console.log(err);
},
//...
});
```

Browser Console Output:

```shell
{
"data": {
"errors": {
"Exception": [
"Class \"App\\Http\\Controllers\\Records\" not found"
]
},
"message": "Exception"
},
"success": false,
"code": 500
}
```

Where,
- `success`: always `FALSE`.
- `code`: contains the error code `419`, `500`, etc.

The `data` property will always contain two properties:
- `message`: This property contains the main error.
- `errors`: contains an object where each property has an array of different errors related to the same issue.

An important thing is how you should return errors from controllers to make reading from the front end more convenient:

```php
try {

//...

} catch (\Throwable $th) {

return response()->json([
"Exception" => $th->getMessage(),
// "Error 2" => "Message Error",
// "Other Errors" => [
// 'Sub Message Error 1',
// 'sub Message Error 2'
// ],
], 500);

}
```

Simply, if you notice, it's an indexed array.

/**
* Salida de Consola
*/
**Convert Them to an Array**

If you need to work with an array instead of an object, perhaps to iterate and print errors in a list, you may find it convenient to use `QuickRequestErrors`. It's a simple utility to convert the error object into an array of objects.

Executing this:

```javascript
QuickRequest.get({
//...
error: function(err){
console.log(
QuickRequestErrors.setErrors(err.data.errors).toArray()
);
},
//...
});
```

Now you'll get the following output:

```shell
[
{
"Exception": [
"Class \"App\\Http\\Controllers\\Record\" not found"
]
}
]
```

You might prefer a flattened array; you can achieve it easily like this:

```javascript
QuickRequest.get({
//...
error: function(err){
console.log(
QuickRequestErrors.setErrors(err.data.errors).toArrayflatten()
);
},
//...
});
```

Now the output is clearer and easier to handle with a loop:

```shell
[
{
"Exception": "Class \"App\\Http\\Controllers\\Record\" not found"
}
]
```
13 changes: 11 additions & 2 deletions src/JS/QuickRequest/QuickRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,16 @@ class QuickRequestFetch {

// Check input elements
const inputsCheck = new QuickRequestElements();
const controls = Array.from(document.getElementById(originForm).elements);

//Validate Form
let controls = [];
const realElementForm = document.getElementById(originForm);
if (realElementForm) {
controls = Array.from(realElementForm.elements);
} else {
throw new QuickRequestException("Could not find any form with the id " + originForm);
}


controls.forEach(element => {

Expand Down Expand Up @@ -951,7 +960,7 @@ const QuickRequestErrors = {

toArrayflatten: function(){
let errors = [];
for (const [key, value] of Object.entries(err.data.errors)) {
for (const [key, value] of Object.entries(this.config.errors)) {
if (Array.isArray(value)) {
value.forEach(element => {
errors.push({
Expand Down
2 changes: 1 addition & 1 deletion src/JS/QuickRequest/QuickRequest.min.js

Large diffs are not rendered by default.

0 comments on commit f42d50b

Please sign in to comment.