Get unique id from database Javascript

Hej guys, I’m doing an event website where you can press on an event and get a ticket nr, the ticket nr get’s saved in a database and now I want to be able to verify the ticket number on a verification page.

this is how the events look like in the database. They all have uniqueKeys which have a number that i want to verify but i don’t know how to get it from the database.

{"id":1,"title":"Lasse-Stefanz","location":"Kjell Härnqvistsalen","time":"19:00 - 21:00","date":"21 mars","price":350,"uniqueKey":9369,"_id":"xmaMvsJBEy6ckPQB"}

{"id":2,"title":"Pelle Trubadur","location":"Pubelipuben","time":"22:00 - 00:00","date":"29 mars","price":110,"uniqueKey":4535,"_id":"zESHeyXmgwhXgHgn"}

{"id":4,"title":"Klubb Untz","location":"Din favoritkällare","time":"22:00 - du tröttnar","date":"17 april","price":150,"uniqueKey":18,"_id":"zjUHDA5gVsxzxJCx"}
´´´

Tranforming axios causes jest test to fails when using MSW

I got a test like this:

it.only('shows loading when fetching', async () => {
    mockServer.use(
      rest.get('*', (req, res, ctx) => {
        TestHelper.sleep(500)
        return res(ctx.status(200), ctx.json({}))
      })
    )
    // @ts-ignore
    const utils = TestHelper.renderWithReactQueryClient(<OverviewScreen navigation={mockNavigation} />)

    await utils.findByText('Henter oplysninger')
  })

this works just fine. But when I add the following transformers

axios.defaults.transformRequest = [humps.decamelizeKeys, JSON.stringify] as AxiosRequestTransformer[]
axios.defaults.transformResponse = [JSON.parse, humps.camelizeKeys] as AxiosResponseTransformer[]

the test fails with

    SyntaxError: Unexpected end of JSON input
        at Object.parse (<anonymous>)

      at transform (node_modules/axios/lib/core/transformData.js:18:15)
      at Object.forEach (node_modules/axios/lib/utils.js:245:10)
      at Object.transformData (node_modules/axios/lib/core/transformData.js:17:9)
      at onAdapterResolution (node_modules/axios/lib/core/dispatchRequest.js:62:35)
      at tryCallOne (node_modules/react-native/node_modules/promise/lib/core.js:37:12)
      at node_modules/react-native/node_modules/promise/lib/core.js:123:15
      at flush (node_modules/asap/raw.js:50:29)

The application works fine – so guessing it’s something with jest and node??

I don’t understand why and would appreciate any suggestions.

How to store and retrieve date in MySQL based on users local time

I would like a user to be able to store information and their current date be recorded.

I am currently using a datetime field to store the users current_date.

  1. Firstly, can the datetime column store a users local time or will it always convert the date to the servers local time?

Currently it seems to be storing the date UTC although I am testing in UTC+10.

  1. Secondly, is there a way to convert the MySQL datetime to the users local date in the select statement?

I have tried this, but it doesn’t do what I am after:

SELECT CONVERT_TZ(current_date,'GMT','MET');
  1. If none of the above is possible, should I just use Javascript’s new Date() function and then store it as a string in the MySQL table.

How to validate multiple file extensions with joi?

Let’s say i want the user to upload only one of two types of files (pdf and docx).
i will validate the file using joi.

Can you confirm is this code correct or not?

const joi = require('@hapi/joi')


const validateFormData = data => {

const shema = joi.object({
    cv: joi
        .string()
        .valid(['application/msword', 'application/pdf'])
        .required()
})
return shema.validate(data, { abortEarly: false })
}

module.exports = {
    validateFormData
}

React Checkbox unlock button

I have to make User Rules page, where will have different pages coming from our API and for every page will have a different rule, Operator, Admin, Moderator. I’m facing a problem with checkboxes which has to give access to choose a rule when is checked.
How to make the logic so every row checkbox to unlock only his row buttons ?
UI of Admin Rule page

                          <TableRow key={index}>
                                <TableCell padding="checkbox">
                                    <Checkbox
                                        color="primary"
                                        size='small'
                                        name='menus'
                                        value={`${row.MENU_ID}`}
                                        onChange={(event) => handleChange(event, index, row)}
                                    />
                                </TableCell>
                                <TableCell component="th" scope="row">
                                    {row.MENU_TITLE}
                                </TableCell>
                                <TableCell>
                                    <Stack direction="row" spacing={4}>
                                        <ToggleButtonGroup
                                            exclusive
                                            aria-label="text alignment"
                                            disabled={isDisabled}
                                            key={index}
                                        >
                                            <ToggleButton value="O" aria-label="left aligned">
                                                O
                                            </ToggleButton>
                                            <ToggleButton value="A" aria-label="centered">
                                                A
                                            </ToggleButton>
                                            <ToggleButton value="M" aria-label="right aligned">
                                                M
                                            </ToggleButton>
                                        </ToggleButtonGroup>
                                    </Stack>
                                </TableCell>
                            </TableRow>

Here is my handleChange Where i take the menuId and save it in array, so i can send it to the Database

const handleChange = (event, index, row) => {
        for (let i = 0; i < menuArr.length; i++) {
            if (menuArr[i] === event.target.value && !event.target.checked) {
                menuArr.splice(i, 1);
                i--;
            }
        }
        if (event.target.checked) {
            menuArr.push(event.target.value);
        }
    }

Google Maps JS API v3 – Compare Coordinates from DB with Result of Google Maps Search

I’m using the Google Maps Javascript API v3 and have a Database with many different Objects at different Coordinates (inside the DB I’m storing the Latitude and Longitude).
Now I’m using a DB Query to display all the Objects (with all the corresponding Informations) on my Website.
I use the Google Maps Api to display a Map with all the Objects (Marker) on it and on Top of that I have a Google Maps Search integrated and I’m already able to receive the Results of the Search Queries.

But now I want to display only the Objects that are inside of the Search Result (for example – if the User searches for a Country, it should display all Objects inside of that Country, if the User searches for a City, it should display all Objects inside of that City and if the User searches for a Street, it should display all Objects on that Street).
Just checking the DB for Objects where the City Name or Street Name match the Query is not an Option, because there are many different Cities / Streets that share the same Name.

I do know that Google Maps is returning the Bounds of the Search Query. But those are just 4 Coordinates, so it’s not accurate enough (I suggest I would need the Coordinates of the Polygon to the searched Country / City / Street..).

Is there any way to validate if the Objects (the Coordinates of the Object to be more precise) match my Search Query?
The only workaround I have found, is using self created Polygons, but because the Objects are flexible Contents, that is not a Solution for me.

Thanks in Advance for any Help or Guidance and Sorry for any Mistakes in my Spelling (English is not my native Language).

automatically specify variables types by their inits in functions

So currently I have this snippet of code outside of any function:

...
/** @type Phaser.Physics.Arcade.Group */
var stars;
var score = 0;
/** @type Phaser.GameObjects.Text */
var scoreText;
/** @type Phaser.Physics.Arcade.Group */
var bombs;
...

The variables are initialised in a function, and because of that if I remove the JsDocs then try to access any of these variables outside of that function (like another function) they will be of type “any” which will not give me code completion.
Now, I wonder if there’s anything better than JsDocs to avoid “any”.

Any help would be appreciated.

Why simple ajax functionality is not workng in Laravel

I am trying to change the message on the button click with ajax in laravel but for some reason, it is not working. I searched it online. Most of the insertion of jquery or ajax links is a problem. I think I’ve entered that correctly, I don’t know what else can be an issue.

There is also no issue in the console of the browser.

Scripts Links in my main layouts.app class


    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>
    {{-- <script type="text/javascript" src="{{ asset('js/custom.js') }}"></script> --}}

    <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
    <!-- JQUERY -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"
        integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg=="
        crossorigin="anonymous"></script>
    <script src="https://markcell.github.io/jquery-tabledit/assets/js/tabledit.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-migrate-3.3.2.min.js"
        integrity="sha256-Ap4KLoCf1rXb52q+i3p0k2vjBsmownyBTE1EqlRiMwA=" crossorigin="anonymous"></script>
    <!-- Bootstrap js -->
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
        integrity="sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp+tA7hAShOK/B/fQ2" crossorigin="anonymous">
    </script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous">
    </script>


Code inside .blade.php

    <div id='msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
    <button id='btn' type="button" class="btn btn-secondary btn-rounded btn-sm my-0">
        Replace Message
    </button>

ajax script inside the same blade.

<script>
$(document).ready(
   $("btn").on("click", 
        function() {
        $.ajax({
          type:'POST',
          url:'/getmsg',
          data:'csrf-token = <?php echo csrf_token() ?>',
          success:function(data) {
            dd(":1");
             $("#msg").html(data.msg);
            }
        });
      }); 
    )
</script>

web.php linking

Route::post('/getmsg', [CustomerController::class, 'index']);

index function inside the CustomerController

    public function index()
    {
        $msg = "This is a simple message.";
        return response()->json(array('msg' => $msg), 200);
    }

Calculate the string length of only characters (not symbols) in the string using Javascript

I am trying to select words being passed through an IF statement based on only their character length, ignoring symbols.

For example If I have the word “hello!” I want the if statement to recognise it as a length of 5 characters.

I want to keep the symbol in the word when it is then added to updatedString. I just don’t want to count the symbol in the original count. I have spent a while considering regex options but am struggling to find something that would work in this particular case.

An example of part of the code is below. (updatedString is declared outside of the if-loop)

 for (let word in arr) {
   if (arr[word].length == 5 || arr[word].length == 6) {
      let bold = arr[word].slice(0, 3)
      let normal = arr[word].slice(3)
      updatedString += `<b>${bold}</b>${normal} ` 
    }
   else if {
   ...
  }
 }

What I ultimately want is the area “arr[word].length == 5” to only count characters.

For the sake of this program I will assume that all words input in via the user will be those used in normal news or academic articles and nothing too obscure.

Any advice would be greatly appreciated, thanks.

Next.js render pages issue with getInitProps

I am implementing protecting routes in Next.js, on each page I added:

export async function getStaticProps(context) {
  return {
    props: {
      protected: true,
    },
  };
}

After included getStaticProps on each page, I started getting the next error in _document.jsx getInitProps:

enter image description here

This is the exact place where error happens:

    ctx.renderPage = () => originalRenderPage({
       enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
     });

This is _document.jsx file

static async getInitialProps(ctx) {
   const sheet = new ServerStyleSheet();
   const originalRenderPage = ctx.renderPage;

   try {
     ctx.renderPage = () => originalRenderPage({
       enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
     });

     const initialProps = await Document.getInitialProps(ctx);
     return {
       ...initialProps,
       styles: (
         <>
           {initialProps.styles}
           {sheet.getStyleElement()}
         </>
       ),
     };
   } finally {
     sheet.seal();
   }
}

Any idea what is the error? I am trying to understand where is a problem