Executing code pre and post mutation graphql neo4j apollo server

I’m just getting started with GraphQL and I’ve worked mostly with featherjs to build REST APIs so far. There’s the concept of hooks to run code before or after interacting with a service. I wanted to know if there’s a way to achieve something similar in a graphql setup.

The specific stack I’m using is neo4j and graphql, express, and apollo server. Since neo4j has a graphql module, I’m not writing the general queries and mutations, just the model types.

For a concrete example, below is a basic API server. It’s put together using docker compose and has users and applications. I would like to in general be able to run arbitrary code before or after a mutation with access to the model being modified. Things like more complex validation before, or side effects after.

Those things could be here, for example, before changing the state of an application to declined, make sure that a note is added. Or after changing the state to approved, send an email to the applicant.

I’m not sure how or where to implement this kind of thing, any help is appreciated! Or also if I’m thinking about graphql wrong and there’s a better way of doing what I’m trying to do.

Thanks!

import http from 'http';
import express from 'express';
import neo4j from 'neo4j-driver';
import {Neo4jGraphQL} from '@neo4j/graphql';
import {gql, ApolloServer} from 'apollo-server-express';
import {ApolloServerPluginDrainHttpServer} from 'apollo-server-core';

const typeDefs=gql`
type User {
    email: String!
    applications: [Application!] @relationship(type: "APPLICANT", direction: OUT)
}

type Application {
    user: User! @relationship(type: "APPLICANT", direction: IN)
    state: String!
    note: String
}
`;

const driver=neo4j.driver(
    'neo4j://neo4j:7687',
    neo4j.auth.basic('neo4j', 'password')
);

const {schema}=new Neo4jGraphQL({typeDefs, driver});

(async ()=>{
    const app=express();
    const server=http.createServer(app);
    const apollo=new ApolloServer({
        schema,
        plugins: [ApolloServerPluginDrainHttpServer({httpServer: server})]
    });
    await apollo.start();
    apollo.applyMiddleware({app});
    await new Promise(r=>server.listen({port: 4000}, r));
    console.log('GraphQL server listening at '+apollo.graphqlPath);
})();

Ionic/Capacitor React App API Requests returning HTML on iOS

The current behavior:

All API requests to the localhost server are returning the index.html file of the React.js app on the iOS build, but requests work fine on browser and PWA builds.

The expected behavior:

Requests return the intended data (usually JSON)


Details

Typically, API requests go to localhost:5000/api/[route]. In the iOS build they are going to capacitor://localhost/api/[route]

Because the route is returning HTML and not JSON data, I am getting the following error (one of many, as each API route, has the same error) which causes a white screen:

TypeError: undefined is not a function (near '...a.map...')

I tried adding a hostname (location where the production server is hosted) to the capacitor.config.json file in my root directory, but it still fails. Dev API server is running on localhost:5000

How can I route my requests on the iOS build to direct to the correct location?

How to do I set the default value for a member of the type BOOLEAN_FIELD in a derived class from foundry.abstract.DocumentData in foundry vvt?

Is there a hook / overwriteable function, when a placeable foundry vvt object was succesfully added to the scene and is ready to be used?

calling

const myown_data = { give_me_icecream: true }
canvas.scene.updateEmbeddedDocuments('ContainerName',[{ _id: this.data._id, ...myown_data }])

in

 _onCreate

complains that the data could not be written / saved when I create the object. But when I reload the scene the data is written to all objects of the type without a problem. I would like to just to set some default values for a BOOLEAN_FIELD or any other DocumentField in a foundry.abstract.DocumentData Class, which should be used only when the object is created for the first time.

jQuery functions not available after compilation

After the compilation of Javascript file with Browserify/Babel (preset-end) or Rollup.js there is not reponse from the script, in the browser. What I want to do is to write a script including node_modules and to transpile it in Javascript browser compatible.

The setup I used with Gulp:

function babel_client() {
    return src('./client/js/Controller_ui.js')
        .pipe(babel({
            presets: [
                [
                    "@babel/preset-env",
                    {
                        "useBuiltIns": "usage",
                        "corejs": "3.10.0"
                    }
                ]
            ]
        }))
        .pipe(dest('build/'));
}

function rollup_client() {
  return src('./client/js/Controller_ui.js')
        .pipe(rollup({
      input: './client/js/Controller_ui.js',
            external: ['jquery'],
            output: {
                format: 'iife',
                globals: {
                    jquery: '$'
                }
            }
    }))
    .pipe(dest('./build'));
}


function lint_client() {
    return src('./client/js/Controller_ui.js')
        .pipe(jshint());
}

function browserify_client() {
    return src('./build/Controller_ui.js')
        .pipe(browserify({
            insertGlobals: true
        }))
        .pipe(rename('Controller_uix.js'))
        .pipe(dest('./public'));
}


exports.browserify = series(lint_client, rollup_client, browserify_client);
exports.build = series(lint_client, rollup_client, node_server, browserify_client);

Controller_ui.js file user by rollup_client or babel_client function

'use strict';

//var $ = require('jquery');
import $ from 'jquery';

window.$ = $;

console.log(window);

$(window).ready(function () {
  console.log('aaäö');
});

the transpile file looks like this

(function ($) {
  'use strict';

  $ = $ && $.hasOwnProperty('default') ? $['default'] : $;

  window.$ = $;

  console.log(window);

  $(window).ready(function () {
    console.log('aaäö');
  });

}($));

looks good, there seems to be wrapped in a function so the browser will not output the content od the function untless it is called. Also if the jquery plugin is included with browserify, there is still no response from the browser.

What will be the best resolution in this regard, Bower?

Get the referenced value of a CSS variable

Given

<div></div>

<style>
body {
  --var1: 3;
  --var2: var(--var1);
}

div {
  --var3: var(--var2);
  width: var(--var3);
}
</style>

How can I obtain the reference list of css variables?

getReferenceList(divElement, 'width')

Would result in

['--var3', '--var2', '--var1', 3]

Why is the fetch request time and request time displayed in the Chrome Network Timing tab different?

I am trying to understand why the total fetch request time logged by my application is different than the time displayed in the Chrome Dev Tools “Network > Timing” tab.

Consider this example that logs the difference between the fetch start time & the time of the fetch response:

const startTime = new Date();
fetch('https://somedomain.com/api/route')
  .then(res => {
    const completeTime = new Date().getTime();
    console.log(completeTime - startTime)
  })

Now, when I check Chrome’s “Network” tab, click on the request in the list and then click on the “Timing” tab- I am presented with a breakdown of the different phases of the request with the total time listed at the bottom. This time is always less than the time logged from example above. Normally the difference is 1-10ms but I have observed differences as high as a several hundred milliseconds.

What factors influence this difference?

Passing Async State to Next.js Component via Prop

I’m fetching WordPress posts asynchronously via getStaticProps()

export async function getStaticProps({ params, preview = false, previewData }) {
    const data = await getPostsByCategory(params.slug, preview, previewData)
    return {
        props: {
            preview,
            posts: data?.posts
        },
    }
}

… and passing them to useState:

const [filteredArticles, setFilteredArticles] = useState(posts?.edges)

Then, I pass the state to a component:

router.isFallback ? (
    // If we're still fetching data...
    <div>Loading…</div>
) : (
    <ArticleGrid myArticles={filteredArticles} />

This is necessary because another component will setFilteredArticles with a filter function.

But when we are passing the state to ArticlesGrid, the data is not ready when the component loads. This is confusing to me since we passing the state within a router.isFallback condition.

Even if we set state within useEffect

const [filteredArticles, setFilteredArticles] = useState()
useEffect(() => {
    setFilteredArticles(posts)
}, [posts?.edges])

… the data arrives too late for the component.

I’m new to Next.js. I can probably hack my way through this, but I assume there’s an elegant solution.

Hide functions/vuex module from clientside?

I have a vuex module that i want to be used/imported only when the user call its, but when i import it in the vuex.modules it imports globally so the functions can be viewed from devtools.

I read functions/modules could be hidden with SSR either using Nuxt or another library.
Is this possible? is there a way to hide functions/modules from the client-side either using vuex or not?

Thanks.

Can I patch a function in one webpack bundle from another at runtime?

I am writing a plugin for a third-party web application, whose code I can see but can’t modify. I’m running it in Chrome. The main webapp and the plugin are both (separate) webpack bundles. At runtime when the page loads, the webapp fetches the plugin bundles from the same server, and initialises them.

My objective is to make my plugin patch/wrap a function in a module webapp/utils/target.tsx in the application, such that calls to that function from within the webapp have my modified behaviour. I am not at all experienced with javascript, particularly how modules work in browsers.

When the page is fully loaded and the app has loaded my plugin, in Chrome developer tools under Sources -> Page, I see:

localhost:port
.
com.mydomain.myplugin
  <modules for my plugin>
application
  webapp
    .
      <other modules>
      utils
        target.tsx
    webpack

I was thinking I may be able to do something like this:

import(/*webpackIgnore: true*/ 'application/webapp/utils/target').then((target) => {
    oldFunc = target.targetFunc;
    target.targetFunc = function targetFunc(args) {
        // do extra stuff here
        return oldFunc(args);
    }
});

Not surprisingly, this fails (I get Failed to resolve module specifier 'application/webapp/utils/target'). I don’t know if it’s possible to import the module from the main webapp this way.

The webapp also makes various functions available for plugins to call, by attaching them to the window object. So window.AppUtils.targetFunc is accessible globally to call. I also tried doing this:

window.AppUtils.targetFunc = function targetFunc(args) {
    // do extra stuff here
    return oldFunc(args);
}

I would not even expect that to affect calls to targetFunc from within the webapp because they wouldn’t reach the function via this reference. I was surprised to find that it doesn’t seem to work even for cases where I call window.AppUtils.targetFunc directly.

Is what I am trying to do even possible…?

I’m getting an error when I try to add value in my DataBase Uuing MongooDB

I would like to add to my Database using MongooDB values with the following code but when my code is running the data I want to add to my database does not add

const profileModel = require('../DataBase/Schema.js')


function UserTotal(userId,TotalForTheSession){
    const time = new Date();
    
    var TotalTimeUserPath = './Settings/UserDataTotal.json'
    var TotalTimeUserRead = fs.readFileSync(TotalTimeUserPath);
    var TotalTimeUserFile = JSON.parse(TotalTimeUserRead); //ready for use
    
    var theyear = time.getFullYear();
    var themonth = time.getMonth() +1;
    var thetoday = time.getDate();
    
    let DateAllTogether = `${theyear}/${themonth}/${thetoday}`
    
    async function totalTimeDataBase(userId,TotalForTheSession,DateAllTogether){
        let userData
        try{
            userData = await profileModel.modelUser.findOne({userID: userId})
            if (!userData){
                let profile = await profileModel.modelUser.insertMany({
                    userID : userId,
                    totalTime: TotalForTheSession,
                    timeDate: {
                        [DateAllTogether]: TotalForTheSession
                    }        
                })   
            }
            else if (!userData.timeDate[DateAllTogether]){
                await profileModel.modelUser.updateOne({
                    userID:userId, "timeDate": {
                        $add: [[DateAllTogether], TotalForTheSession]
                            
                      },
                },
                )
            }       
        }catch(err){
            console.log(err)
        }
    }   
    totalTimeDataBase(userId,TotalForTheSession,DateAllTogether)

The code for how my Schema in my dataBase is made

const mongoose = require('mongoose')

const profileSchema = new mongoose.Schema({
    userID: {type: String, require: true},
    timeTotal: {type: String, default: 0 },
    timeDate:{}
})



const modelUser = mongoose.model('ProfileModels', profileSchema)


module.exports = {modelUser}



When the code is executed i’m getting this errorMongoServerError: The dollar ($) prefixed field '$push' in 'timeDate.$push' is not valid for storage.*


The file where my data is stored in my database

{
    "_id" : ObjectId("61bd159db3daaef59378e5f1"),
    "userID" : "526166979321790466",
    "timeTotal" : "0",
    "timeDate" : {
        "2021/12/16" : 1
    },
    "__v" : 0
}

I want to add “2021/12/17” : 1 in “timeDate” value like so

{
    "_id" : ObjectId("61bd159db3daaef59378e5f1"),
    "userID" : "526166979321790466",
    "timeTotal" : "0",
    "timeDate" : {
        "2021/12/16" : 1,
        "2021/12/17" : 1
    },
    "__v" : 0
}

hey guys iam trying to create my reacte app an i i have aproblem i dont where i can fix it

hey guys iam trying to create my reacte app an i i have aproblem i dont where i can fix itstrong text
i wrote this code but its not return a data to me and i don’t know where the problem please help
using ccreate a reacct app
hey guys iam trying to create my reacte app an i i have aproblem i dont where i can fix itstrong text
i wrote this code but its not return a data to me and i don’t know where the problem please help
using ccreate a reacct app
//this my app.j s

import Employees from "./Components/Employees";

import "bootstrap/d ist/css/bootstrap.min.css";



export default function App() {
  return (
    <div 
      
      <Employees/>
  

    </div>
  );
}


// this my Employee. j s x
import React,  { useEffect, useState } from "react";

import axios from "axios";

function Employee(props) {
    const [employeeData, setEmployeeData] = useState(null);
    useEffect(
        function(){
           a x i o s
           .get(`http://statenweb.mockable.io/employee/${props.selectedEmployee}`) // this is the data 
           .then(function(response){
               setEmployeeData(response.data);
           });
                
            },
            [props.selectedEmployee]
            
            );
            
            if (!employeeData){
            return <p> loading....</p>;
}

return(
    <div>
        <img 
    style={{ maxHeight: "300px"}}
src={employeeData.photo}

alt={employeeData.name}
/>
<p>{employeeData.name}</p>



    </div>
)
}
export default Employee;


// this my Employees.j s x

import a x i os from "ax i os";
import React,{useEffect, useState} from "react";
//import Employee from "./Employee";


function Employees(){

const [employees, setEmployees] = useState([]);
const [selectedEmployee, setSelectedEmployee] = useState(null);

function getAllEmployees(){

ax i o s . g et("https://statenweb.mockable.io/employees").then(function(response){
setEmployees(response.data);
});
}

if (selectedEmployee){
    return(
        <div>
            <p>you selected a {selectedEmployee}</p>
            
            <button  onClick={() => setSelectedEmployee(null)}>Reset</button>
        </div>
    );
}




return(
    <div>
        <button onClick={getAllEmployees}>get all the employees</button>
        {employees.map(function(employee){
            return(
                <p key={employee.id}>
                    <button  onClick={() => setSelectedEmployee(employee.department)}>
                    my name is {employee.name}- ID: {employee.id}

                        
                    </button>
                </p>
            );
        })}
    </div>

    );
    }

    
export default Employees ;

Click event not firing when input field is active

I have an Angular project with a setup similar to this:

<input type="text" [(ngModel)]="search" >
<app-item-list
    [items]="foundItems"
    (itemClick)="onItemSelected($event)">
</app-item-list>

There’s an input field that the user types in. As they type, the item-list component populates with results.

In the item list component, it simply shows all items passed in, and if one is clicked, it fires the event itemClick

So long as the input remains active, the user must click twice on an item in order for the click event to fire. Clicking anywhere else (to deselect the input field) and then clicking an item also works.

This is supposed to be some sort of search ‘dropdown box’, where typing displays a list of autocomplete-like options fetched from elsewhere. It works fine other than having to click twice. The first click only fires an ngModelChange event and the second fires the itemClick event.

When parts of an image are added, some parts do not? [closed]

Here I have made the head, body and legs separately from Photoshop. I want to add them from JavaScript and create different shapes(actions).

But when it works, the parts fall apart and add up. (Sometimes the head is lost, sometimes the legs are lost, sometimes the body and the head are both lost) Sometimes everything comes together correctly (head+body+leg).

enter image description here