How to fix ' file.writeFile is not a function ' in vuejs - node.js

I am using Vue.js to display json data from a locally stored file in a table on the web page. I also want to update the data in the json file by using data from a form. But I get the error mentioned above
import json from "../assets/data.json";
export default{
json,
data(){
return{
title: '',
date: new Date().toISOString().substr(0, 10),
modal: false,
menu2: false,
dialog: false,
notifications: false,
sound: true,
widgets: false,
task: '',
tasks: {},
}
},
methods: {
submit: function(){
this.tasks = {id: json.length+1, task:this.task,date: this.date, complete: false}
json.push(this.tasks)
var file = require('fs')
file.writeFile('../assets/data.json', json)
}
reset1(){
this.task = '';
this.date = new Date().toISOString().substr(0, 10);
}
},
name: "Form"
};
</script>

Related

Can a push notification be send from the server without a client call?

I have a javascript file on my NodeJS server that runs at 00:00:00 and updates some fields in the database, if that happens I want to send out a push notification to some users. I've set this up in my Javascript file:
https://dev.to/devsmranjan/web-push-notification-with-web-push-angular-node-js-36de
const subscription = {
endpoint: '',
expirationTime: null,
keys: {
auth: '',
p256dh: '',
},
};
const payload = {
notification: {
title: 'Title',
body: 'This is my body',
icon: 'assets/icons/icon-384x384.png',
actions: [
{action: 'bar', title: 'Focus last'},
{action: 'baz', title: 'Navigate last'},
],
data: {
onActionClick: {
default: {operation: 'openWindow'},
bar: {
operation: 'focusLastFocusedOrOpen',
url: '/signin',
},
baz: {
operation: 'navigateLastFocusedOrOpen',
url: '/signin',
},
},
},
},
};
const options = {
vapidDetails: {
subject: 'mailto:example_email#example.com',
publicKey: process.env.REACT_APP_PUBLIC_VAPID_KEY,
privateKey: process.env.REACT_APP_PRIVATE_VAPID_KEY,
},
TTL: 60,
};
webpush.sendNotification(subscription, JSON.stringify(payload), options)
.then((_) => {
console.log(subscription);
console.log('SENT!!!');
console.log(_);
})
.catch((_) => {
console.log(subscription);
console.log(_);
});
But when I run the file I get the message:
{ endpoint: '', expirationTime: null, keys: { auth: '', p256dh: '' } } Error: You must pass in a subscription with at least an endpoint.
Which makes sense since the server has no idea about service workers etc. Any suggestions on how to proceed?

Attempting to save data that is streamed from a twitter api

I am trying to save data from tweets to a mongoDB database using node and express.
I am using the twitter api to stream twitter data with a specific hashtags. I just want to save the text content of the post:
Here is how the tweet content shows up when it is console.logged:
(Note this feature works and this is my own posted
{
created_at: 'Tue Mar 15 06:38:58 +0000 2022',
id: 1503621761388134400,
id_str: '1503621761388134410',
text: '#TelecomDisaster Test for project 2',
source: 'Twitter Web App',
truncated: false,
in_reply_to_status_id: null,
in_reply_to_status_id_str: null,
in_reply_to_user_id: null,
in_reply_to_user_id_str: null,
in_reply_to_screen_name: null,
user: {
id: 1472188612494172200,
id_str: '1472188612494172172',
name: 'Dillon Rampersad',
screen_name: 'R_Dillon_25',
location: null,
url: null,
description: null,
translator_type: 'none',
protected: false,
verified: false,
followers_count: 5,
friends_count: 11,
listed_count: 0,
favourites_count: 22,
statuses_count: 63,
created_at: 'Sat Dec 18 12:55:26 +0000 2021',
utc_offset: null,
time_zone: null,
geo_enabled: false,
lang: null,
contributors_enabled: false,
is_translator: false,
profile_background_color: 'F5F8FA',
profile_background_image_url: '',
profile_background_image_url_https: '',
profile_background_tile: false,
profile_link_color: '1DA1F2',
profile_sidebar_border_color: 'C0DEED',
profile_sidebar_fill_color: 'DDEEF6',
profile_text_color: '333333',
profile_use_background_image: true,
profile_image_url: 'http://pbs.twimg.com/profile_images/1472188757956780033/OMlZZeZI_normal.jpg',
profile_image_url_https: 'https://pbs.twimg.com/profile_images/1472188757956780033/OMlZZeZI_normal.jpg',
default_profile: true,
default_profile_image: false,
following: null,
follow_request_sent: null,
notifications: null,
withheld_in_countries: []
},
geo: null,
coordinates: null,
place: null,
contributors: null,
is_quote_status: false,
quote_count: 0,
reply_count: 0,
retweet_count: 0,
favorite_count: 0,
entities: { hashtags: [ [Object] ], urls: [], user_mentions: [], symbols: [] },
favorited: false,
retweeted: false,
filter_level: 'low',
lang: 'en',
timestamp_ms: '1647326338513'
}
I want to save text: '#TelecomDisaster Test for project 2', and created_at: 'Tue Mar 15 06:38:58 +0000 2022', to my database.
I am trying with the function below to save just the text for now but i dont quite understand how to:
const express = require('express')
const router = new express.Router();
var Twitter = require('twit')
const TwitterPosts = require("../db/models/TwitterPosts.model");
//api keys goes here but it removed for safety
var stream = client.stream('statuses/filter', { track: '#TelecomDisaster' })
stream.on('tweet', function (tweet) {
console.log(tweet)
let newtweet = new TwitterPosts({
tweet: req.body.postContent
});
newtweet.save().then((twit) => {
res.send(twit);
console.log(twit);
})
});
module.exports = router;
The model for the schema:
const mongoose = require('mongoose');
const TwitterPostsSchema = new mongoose.Schema({
twitterUsername:{
type: String,
required: false,
minlength:1,
trim: true
},
postContent:{
type: String,
required: false,
minlength:1,
trim: true
},
postDateTime:{
type: Date,
required: false,
default: Date.now
}
})
const TwitterPosts = mongoose.model( 'TwitterPosts', TwitterPostsSchema);
module.exports = TwitterPosts
Whenever it trys to save i get the error
tweet: req.body.postContent
^
ReferenceError: req is not defined
i did not define req but in this use case i dont know how to do that exactly when streaming the tweets.
To conclude i am trying to save tweets to a mongoDB database using node and express. the tweets are streamed as shown above but i dont quite understand how it is saved to the database.
you receive tweet in stream.on listener, so it's just tweet, instead of req.body.postContent:
let newtweet = new TwitterPosts({
tweet: tweet
});
or, according to your schema:
let newtweet = new TwitterPosts({
twitterUsername: tweet.user.name,
postContent: tweet.text,
postDateTime: tweet.created_at
});

Apollo GraphQL Server - Access query params from cache plugin

I have an Apollo GraphQL server using the apollo-server-plugin-response-cache plugin and I need to determine whether or not I'm going to write to the cache based on incoming parameters. I have the plugin set up and I'm using the shouldWriteToCache hook. I can print out the GraphQLRequestContext object that gets passed into the hook, and I can see the full request source, but request.variables is empty. Other than parsing the query itself, how can I access the actual params for the resolver in this hook? (In the example below, I need the value of param2.)
Apollo Server:
new ApolloServer({
introspection: true,
playground: true,
subscriptions: false,
typeDefs,
resolvers,
cacheControl: {
defaultMaxAge: 60
},
plugins: [
apolloServerPluginResponseCache({
cache, // This is a "apollo-server-cache-redis" instance
shouldWriteToCache: (requestContext) => {
// I get a lot of info here, including the source query, but not the
// parsed out query variables
console.log(requestContext.request);
// What I want to do here is:
return !context.request.variables.param2
// but `variables` is empty, and I can't see that value parsed anywhere else
}
})
]
})
Here is my resolver:
export async function exapi(variables, context) {
// in here I use context.param1 and context.param2
// ...
}
I have also tried:
export async function exapi(variables, { param1, param2 }) {
// ...
}
Here is what I get logged out from the code above:
{
query: '{\n' +
' exapi(param1: "value1", param2: true) {\n' +
' records\n' +
' }\n' +
'}\n',
operationName: null,
variables: {}, // <-- this is empty?! How can I get param2's value??
extensions: undefined,
http: Request {
size: 0,
timeout: 0,
follow: 20,
compress: true,
counter: 0,
agent: undefined,
[Symbol(Body internals)]: { body: null, disturbed: false, error: null },
[Symbol(Request internals)]: {
method: 'POST',
redirect: 'follow',
headers: [Headers],
parsedURL: [Url],
signal: null
}
}
}
If you didn't provide variables for GraphQL query, you could get the arguments from the GraphQL query string via ArgumentNode of AST
If you provide variables for GraphQL query, you will get them from requestContext.request.variables.
E.g.
server.js:
import apolloServerPluginResponseCache from 'apollo-server-plugin-response-cache';
import { ApolloServer, gql } from 'apollo-server';
import { RedisCache } from 'apollo-server-cache-redis';
const typeDefs = gql`
type Query {
exapi(param1: String, param2: Boolean): String
}
`;
const resolvers = {
Query: {
exapi: (_, { param1, param2 }) => 'teresa teng',
},
};
const cache = new RedisCache({ host: 'localhost', port: 6379 });
const server = new ApolloServer({
introspection: true,
playground: true,
subscriptions: false,
typeDefs,
resolvers,
cacheControl: {
defaultMaxAge: 60,
},
plugins: [
apolloServerPluginResponseCache({
cache,
shouldWriteToCache: (requestContext) => {
console.log(requestContext.document.definitions[0].selectionSet.selections[0].arguments);
return true;
},
}),
],
});
server.listen().then(({ url }) => console.log(`🚀 Server ready at ${url}`));
GraphQL query:
query{
exapi(param1: "value1", param2: true)
}
Server logs print param1 and param2 arguments:
🚀 Server ready at http://localhost:4000/
[]
[ { kind: 'Argument',
name: { kind: 'Name', value: 'param1', loc: [Object] },
value:
{ kind: 'StringValue',
value: 'value1',
block: false,
loc: [Object] },
loc: { start: 15, end: 31 } },
{ kind: 'Argument',
name: { kind: 'Name', value: 'param2', loc: [Object] },
value: { kind: 'BooleanValue', value: true, loc: [Object] },
loc: { start: 33, end: 45 } } ]

can't get data-labels in highcharts-export-server on live server

i am using highcharts-export-server for export charts and send it to Email in PDF format
while i am trying to export that in localy it was working fine, but on live server when i am trying to export all the charts data-labels disappear.
this is the image from which was exporting from live server.
and here is the image which was exporting locally.
Here is my Code
exports.getPieChartImg = (seriesData, xOrLength, innersize, showLegend, width, height) => {
var chartOpts = {
chart: {
type: 'pie',
width: width,
height: height,
},
plotOptions: {
pie: {
innerSize: innersize || 80,
depth: 25,
allowPointSelect: true,
dataLabels: {
enabled: false,
format: '<b>{point.name}</b>: {point.percentage:.2f} %'
},
showInLegend: showLegend || false,
},
series: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: '#6f6f6f',
format: '{point.percentage:.2f}',
crop: false,
overflow: "none",
},
pointWidth: 30,
}
},
legend: {
labelFormat: '<b>{name}</b> ({percentage:.2f})%',
useHTML: true,
},
series: [{
data: seriesData
}]
};
var exportSettings = generateExportSettings(chartOpts, 'Pie');
return generateBase64Chart(exportSettings)
}
function generateExportSettings(chartOpts, constr) {
return {
// b64: true,
instr: JSON.stringify(chartOpts),
noDownload: true,
constr,
globalOptions: {
colors: ['#3BB9DA', '#0F89A8', '#0B8F8B', '#1DB1AD', '#68E3DF', '#FFB469', '#F58B1F', '#D16900', '#FC3C3C', '#FF6666', '#FC8D8D', '#FCC0C0'],
lang: {
thousandsSep: ','
}
},
scale: false,
styledMode: false,
type: "image/png",
width: false,
};
}
function generateBase64Chart(exportSettings) {
return new Promise((resolve, reject) => {
highchartsExporter.export(exportSettings, function (err, res) {
if (err) {
return reject({
code: '1',
err,
msg: 'Error in stock chart',
exportSettings
})
}
return resolve({
code: '0',
msg: 'success',
data: 'data:image/png;base64,' + res.data,
})
});
})
}
remove node_module and reInstall it again.
and if not installed libfontconfig then install 'sudo apt-get install libfontconfig'

jqgrid - filter/search always gives me only "contains" operator for a option

I am using jQgrid - and it is great!
I have one problem.
(Oleg are you still around?)
In the search/filter form (were you can choose the coulmn you want to filter and the operation you want do to), the only things that comes up is the "contain" operator.
My colModel looks like this:
var columnModel = [{ name: 'ID', index: 'ID', sortable: true, searchoptions: { sopt: ['eq', 'cn','bw']}},
{ name: 'FirstName', index: 'FirstName', sortable: true},
{ name: 'LastName', index: 'LastName', sortable: true }
];
But it only gives me the contains operator.
The full grid is like this:
myGrid.jqGrid({
url: './ViewNQueryData.asmx/ViewNQueryData',
datatype: 'json',
mtype: 'POST',
postData: {userID:currentUserId, sphereID:currentSphereId},
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData)
{
if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) { return obj.d.rows; },
page: function (obj) { return obj.d.page; },
total: function (obj) { return obj.d.total; },
records: function (obj) { return obj.d.records; }
},
colModel: columnModel,
colNames: columnNames,
rowNum: 10,
rowList: [10, 20, 300],
sortable: true,
pager: "#ViewNQueryPager",
viewrecords: true,
gridview: true,
height: 250,
shrinkToFit: true, //If using frozen coulmns change to false.
gridComplete: function ()
{
$('#totalRecordsFound').html(myGrid.jqGrid('getGridParam', 'records') + " Customers");
},
loadError: function ()
{
alert("Error fetching data");
}
}).jqGrid('navGrid', '#ViewNQueryPager',
{ edit: false, add: false, del: false, search: true, view: true }, //option
{}, // use default settings for edit
{}, // use default settings for add
{}, // delete instead that del:false we need this
{multipleSearch: true, multipleGroup: true, showQuery: true, onSearch: function (response) { showQueryDetails(); } },
{ height: 250, jqModal: false, closeOnEscape: true} // view options
);
Can any one help me with this???
Fixed!
I had a snippet of code on my page that was doing this....

Resources