Vuex without Vue? - node.js

I'd like to use Vuex to power a server-side application that doesn't use Vue. Is this possible?
const Vuex = require('vuex');
const store = new Vuex.Store({
state: {
potatoes: 1,
},
getters: {
doublePotatoes(state) {
return state.potatoes * 2;
},
},
mutations: {
addPotato(state) {
state.potatoes += 1;
},
}
});
store.watch((state, getters) => getters.doublePotatoes, console.log);
store.commit("addPotato");
Here's the error I get:
$ node index.js
/private/tmp/vtest/node_modules/vuex/dist/vuex.common.js:99
if (!condition) { throw new Error(("[vuex] " + msg)) }
^
Error: [vuex] must call Vue.use(Vuex) before creating a store instance.
at assert (/private/tmp/vtest/node_modules/vuex/dist/vuex.common.js:99:27)
at new Store (/private/tmp/vtest/node_modules/vuex/dist/vuex.common.js:279:5)
at Object.<anonymous> (/private/tmp/vtest/index.js:3:15)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)

I wound up adding Vue without creating a Vue app:
const Vue = require('vue');
Vue.use(Vuex);
My tiny test store works now. I don't know if Vue.use(Vuex) without creating a Vue app will cause any problems.
Of note for server-side use cases, Vuex doesn't call my watcher for every commit; it batches changes and calls the watcher once. I don't see this documented.

Related

Node - Migrate postgres DB programmatically using jest globalsetup.js file

I am trying to use testcontainers(https://github.com/testcontainers/testcontainers-node/tree/master/src/modules/postgresql) to spin up a postgres db and use that to run my jest tests.
I used globalsetup.js file to run the container spinup code. The container is spinning successfully, no problem in that, but the issue arises when i try to migrate the db. For Migrating i use typeorm's connection.runMigrations function. Somehow the migration is not working.
All my files, except globalsetup.js is a typescript file.
My connection string looks like this:
createConnection({
url: `postgres://${username}:${encodeURIComponent(password)}#${host}:${port}/${database}`
entities: process.env.TYPEORM_ENTITIES.split(‘,’),
migrations: process.env.TYPEORM_MIGRATIONS?.split(‘,’),
type: 'postgres,
});
TYPEORM_ENTITIES=src/db/entities/**/.ts
TYPEORM_MIGRATIONS=src/db/migrations/.ts
and in my jest.globalSetup.js:
const {createConnection} = require('typeorm')
module.exports = async () => {
/* Code for Container Startup */
process.env.NODE_ENV = ‘test’;
const connection = await createConnection({
url: `postgres://uno-test:dia#localhost:${process.env.TYPEORM_PORT}/cart-test?sslmode=disable`,
entities: process.env.TYPEORM_ENTITIES.split(‘,’),
migrations: process.env.TYPEORM_MIGRATIONS?.split(‘,’),
type: ‘postgres’,
});
await connection
.runMigrations()
.then((value) => console.log(‘Migration Done’, value))
.catch((e) => console.log(e));
await connection
.close()
};
Error Message is:
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from ‘typeorm’;
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at /Users/webmaster/CART/cart-portal-service/node_modules/typeorm/util/ImportUtils.js:29:52
at step (/Users/webmaster/CART/cart-portal-service/node_modules/tslib/tslib.js:144:27)
I tried changing the entities and migrations constants to
TYPEORM_ENTITIES=src/db/entities/**/.{ts,js}
TYPEORM_MIGRATIONS=src/db/migrations/.{ts,js}
If i do above chagne, I no longer see the error, but my db is empty as in no tables are created.
Versions:
Node - 16.6.0
Typeorm - 0.2.45
typescript: 4.7.4
jest: 28.1.3

Read file and write file JSON

In this, I am trying to make a hit counter where every time someone visits my site the variable will be read from the views.json file one is added to the number and then the .json will be updated with the new number. However when I tested it in a repl.it project I got an error saying
ReferenceError: writeFileSync is not defined
at /home/runner/hit-counter/index.js:6:1
at Script.runInContext (vm.js:133:20)
at Object.<anonymous> (/run_dir/interp.js:156:20)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
I don't know what this means if you know please tell me and how I may be able to fix it.
the reply project link:https://hit-counter.cohense.repl.run/
The JavaScript (ES6)
const fs = require('fs');
let views = fs.readFileSync('views.json');
views = JSON.parse(views);
views.total++;
let data = JSON.stringify(views, null, 2);
writeFileSync("views.json", data, finished);
function finished(err) {
if (views = JSON.parse(views)) {
console.log("Your view has been accounted for!")
} else {
console.error("Error occured please reload the page =(")
}
};
the JSON
{
"totalViews": 1
}
You can do like this, just fixed some errors.
Oh, you should use writeFileSync, to avoid that the file will not be edited at same time.
The question is, why don't you use a DB? It's a lot faster and fix concurrency writes.
var fs = require('fs')
var data = fs.readFileSync('views.json')
var views = JSON.parse(data);
console.log(views);
views.total = views.total + 1;
var data = JSON.stringify(views, null, 2)
writeFileSync("views.json", data, ()=>{
console.log("Your View Has Been Accounted For!")
})
I found out what I did wrong I didn't use fs.
writeFileSync("views.json", data, finished);
When I just needed to do
fs.writeFileSync("views.json", data[,finished]);

How to using eventSource on nodejs

I am new on nodejs
ı have a project for server sent events.
I am trying get datas with server sent events on console.
this is my code:
var source = new EventSource('https://sse.now.sh');
source.onmessage = function(e) {
console.log(e.data)
};
but when i try start project with node file.js :
ReferenceError: EventSource is not defined
at Object.<anonymous> (c:\Users\SYDNEY\Desktop\server-sent-events-demo\src\client\js\app.js:7:5)
at Module._compile (internal/modules/cjs/loader.js:953:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at internal/main/run_main_module.js:17:11
its just simple but i couldnt do anyting. should ı download anything about that ? bcz this script working on jsbin(website)
I solved this problem with add top of codes
var EventSource = require('eventsource')
var source = new EventSource('https://sse.now.sh');
source.onmessage = function(e) {
console.log(e.data)
};

Extend SchemaDirectiveVisitor To Use Apollo Server Schema Directives in NodeJS

I'm trying to extend SchemaDirectiveVisitor in order to make a custom directive in Apollo Server 2. I'm specifically using the 2.2.6 hapi node module.
Here's my server.js code:
const { ApolloServer } = require('apollo-server-hapi');
const { SchemaDirectiveVisitor } = ApolloServer;
class ViewTemplateGroup extends SchemaDirectiveVisitor {
visitFieldDefinition(field) {
console.log('Im calling this directive!');
return;
}
}
When I start up my server I immediately get the following error:
TypeError: Class extends value undefined is not a constructor or null
at Object.<anonymous> (/Users/garrett.kim/Desktop/Projects/Test Web/poc-graphQL-forms-gyk/server.js:36:33)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:193:16)
at bootstrap_node.js:617:3
To my knowledge, I'm following the Apollo Server 2 example very closely.
https://www.apollographql.com/docs/apollo-server/features/creating-directives.html
Any help getting directives working would be appreciated.
The ApolloServer class does not have a SchemaDirectiveVisitor property on it; therefore, calling ApolloServer.SchemaDirectiveVisitor results in undefined and a class cannot extend undefined as the error indicates. Just import SchemaDirectiveVisitor directly from the apollo-server-hapi module:
const { ApolloServer, SchemaDirectiveVisitor } = require('apollo-server-hapi')

Can't update elements which are inside the array

Let's say I have this
userinfo={
userDetails:
{
username:"",
password:"",
cookie:"",
firstname:"",
lastname:"",
phonenumber:"",
postalcode:"",
country:""
},
applicationsInfo:[
{
application:"",
consumerKey:"",
accessToken:""
}
]
}
First I created user and latter I am to update applicationsInfo section when user creates an application. First I tried this way and It works
var consumerKey="asdyfsatfdtyafydsahyadsy";
var findCon={"userDetails.username":"someName"};
db.find(findCon,function(err,docs){
if(err){
console.log(err);
}else{
var updateCon={$set:{"applicationsInfo.0.consumerKey":consumerKey}};
db.update(findCon,updateCon,{},function(err,docs){
console.log(docs);
});
}
});
But actually what I want is update some selected one I tried that in this way.
........
var appNum=0;
var updateCon={$set:{"applicationsInfo."+appNum+".consumerKey":consumerKey}};
then I start my node server then I got error like this.
/home/jobs/nodeserver/routes/initusers.js:180
"applicationsInfo."+appNum+
^
SyntaxError: Unexpected token +
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
You need to set it the below way:
var appNum = 0;
var updateCon = {$set:{}};
updateCon.$set["applicationsInfo."+appNum+".consumerKey"] = 1;
Setting an expression ("applicationsInfo."+appNum+".consumerKey") as key of an object during initialization is not allowed in java script.

Resources