Error installing Twit - json

Wanted to see if I could make a bot (just for myself, not to spam. Obviously!) and took the following steps:
Download Node.js from the main site.
Created an app on Twitter and all that stuff.
Tried it a ton of ways and then read this blog: http://www.apcoder.com/2013/10/03/twitter-bot-20-minutes-node-js/
Now, I am here: https://github.com/ttezel/twit I installed it from the terminal and got back:
node_modules/twit
└── oauth#0.9.9
Then I went to include the following (with my Twitter app details included) and got pages and pages of errors. I checked on ShellCheck and it's mostly parsing errors. But as it was just copy and paste, I think I must be doing something else wrong.
Any ideas?
var Twit = require('twit')
var T = new Twit({
consumer_key: '...'
, consumer_secret: '...'
, access_token: '...'
, access_token_secret: '...'
})
//
// tweet 'hello world!'
//
T.post('statuses/update', { status: 'hello world!' }, function(err, data, response) {
console.log(data)
})
//
// search twitter for all tweets containing the word 'banana' since Nov. 11, 2011
//
T.get('search/tweets', { q: 'banana since:2011-11-11', count: 100 }, function(err, data, response) {
console.log(data)
})
//
// get the list of user id's that follow #tolga_tezel
//
T.get('followers/ids', { screen_name: 'tolga_tezel' }, function (err, data, response) {
console.log(data)
})
//
// retweet a tweet with id '343360866131001345'
//
T.post('statuses/retweet/:id', { id: '343360866131001345' }, function (err, data, response) {
console.log(data)
})
//
// destroy a tweet with id '343360866131001345'
//
T.post('statuses/destroy/:id', { id: '343360866131001345' }, function (err, data, response) {
console.log(data)
})
//
// get `funny` twitter users
//
T.get('users/suggestions/:slug', { slug: 'funny' }, function (err, data, response) {
console.log(data)
})
//
// post a tweet with media
//
var b64content = fs.readFileSync('/path/to/img', { encoding: 'base64' })
// first we must post the media to Twitter
T.post('media/upload', { media: b64content }, function (err, data, response) {
// now we can reference the media and post a tweet (media will attach to the tweet)
var mediaIdStr = data.media_id_string
var params = { status: 'loving life #nofilter', media_ids: [mediaIdStr] }
T.post('statuses/update', params, function (err, data, response) {
console.log(data)
})
})
//
// stream a sample of public statuses
//
var stream = T.stream('statuses/sample')
stream.on('tweet', function (tweet) {
console.log(tweet)
})
//
// filter the twitter public stream by the word 'mango'.
//
var stream = T.stream('statuses/filter', { track: 'mango' })
stream.on('tweet', function (tweet) {
console.log(tweet)
})
//
// filter the public stream by the latitude/longitude bounded box of San Francisco
//
var sanFrancisco = [ '-122.75', '36.8', '-121.75', '37.8' ]
var stream = T.stream('statuses/filter', { locations: sanFrancisco })
stream.on('tweet', function (tweet) {
console.log(tweet)
})
//
// filter the public stream by english tweets containing `#apple`
//
var stream = T.stream('statuses/filter', { track: '#apple', language: 'en' })
stream.on('tweet', function (tweet) {
console.log(tweet)
})

Related

Set image in HTML from API request node.js

I have an API request that returns the image of the product that had been saved in the database in the form of buffer in MONGODB. The API returns the image and I want this image as source to my html element. How do I do that?
The API request is:
router.get('/product/avatar/:id', async (req, res) => {
try{
const product = await Product.findById(req.params.id)
if(!product || !product.avatar){
throw new Error()
}
// console.log('product avatar')
res.set('Content-Type', 'image/png')
res.send(product.avatar)
} catch(e) {
res.status(404).send()
}
})
And this is how I was trying to assign that image to my HTML
the code snippet given below is a part of the javascript used to render information on webpage from database.
var picId = data[i].name + 'Image'
// console.log(data[i]._id)
fetch('/product/avatar/'+data[i]._id, {
method: 'GET'
}).then((res) => {
return res.json()
}).then((data) => {
// picId.value = data
// document.getElementById(picId).src = data
console.log(data)
})

My response from api is undefined on frontend

I got list of items from my database mySql and also button 'edit'.
When I clicked edit (by id) I want to see all fields filled by data.
But I only have in my console: undefined
If I tested my api by postman it works fine.
There is how I am getting list.
{
const id = this.actRoute.snapshot.paramMap.get('id');
this.studentApi.GetStudent(id).subscribe((res: any) => {
console.log(res.data);
this.subjectArray = res.data;
console.log(this.subjectArray);
this.studentForm = this.fb.group({
id: [res.id, [Validators.required]],
domain_id: [res.domain_id, [Validators.required]],
source: [res.source, [Validators.required]],
destination: [res.destination]
});
});
}
There is my api.service.ts
GetStudent(id): Observable<any> {
const API_URL = `${this.endpoint}/read-student/${id}`;
return this.http.get(API_URL, { headers: this.headers })
.pipe(
map((res: Response) => {
return res || {};
}),
catchError(this.errorMgmt)
);
}
And there is my route
studentRoute.get('/read-student/:id', (request, response) => {
const id = request.params.id;
con.query('SELECT * FROM students WHERE id = ?', id, (error, result) => {
if (error) throw error;
response.send(result);
});
});
There is response from 'postman'
[
{
"id": 5,
"domain_id": 2,
"source": "tester0700#test.pl",
"destination": "testw#test.pl"
}
]
It seems like the response is an array, containing an object.
In that case, there is no need to use res.data, as that would imply the returned observable, res has a property named data, and that you are trying to access the value within that property. You can simply assign res to the subjectArray property. I am pretty sure res would be defined.
this.studentApi.GetStudent(id).subscribe((res: any) => {
console.log(res);
this.subjectArray = res;
// handle the rest here.
});

Creating a JSON - Angular 5

I have a JSON read to UI and modifiled as part of review process. Finally I want to save New data to a New folder/File.
Code Sample below - Always ends with POST call in error :
SaveFinalData(){
this.postJson<Reaction>
('./assets/ICP/Reviewed/Json/out.json',
this.reactionDatabase.reactiondataChange.value);
}
postJson<Reaction>(url: string, Reaction: any){
//let body = JSON.stringify({ Reaction });
this.http.post(url, body)
.subscribe(
(val) => {
console.log("POST call successful value returned in body", val);
},
response => {
console.log("POST call in error", response);
},
() => {
console.log("The POST observable is now completed.");
});
}
Have tried below 2 alternatives:
(1)
var theJSONdata = JSON.stringify({ Reaction });
window.localStorage.setItem('./assets/ICP/Reviewed/Json/out.json', theJSONdata)
Result -- NO LUCK!
(2)
var jsonfile = require('jsonfile')
var file = './assets/ICP/Reviewed/Json/out.json'
var obj = {name: 'JP'} //SAMPLE DATA
jsonfile.writeFile(file, obj, function (err) {
console.error(err)
})
Result -- NO LUCK! --> GIVES ERROR fs.writeFile is not a function
Pls kindly help/guide me to reach the final result....Thanks

TypeError: database.insert is not a function occurs in Node.js

Up, running and ready for action!
When GET method is used, the below output comes but never completes loading... from POSTMAN Why?
Successfully connected to MongoDB instance!
MongoDB returned the following documents:
[ { _id: ObjectID { _bsontype: 'ObjectID', id: [Object] },
name: 'Apple',
price: 2.5 },
{ _id: ObjectID { _bsontype: 'ObjectID', id: [Object] },
name: 'Pear',
price: 3 },
{ _id: ObjectID { _bsontype: 'ObjectID', id: [Object] },
name: 'Orange',
price: 3 } ]
When POST method is used, the below error occurred. Why?
/Users/json/Dev/restful_api/api.js:21
database.insert('OrderBase', resourceName, resource, function(err, resource) {
^
TypeError: database.insert is not a function
at insertResource (/Users/json/Dev/restful_api/api.js:21:12)
at insertProduct (/Users/json/Dev/restful_api/api.js:34:3)
at IncomingMessage.<anonymous> (/Users/json/Dev/restful_api/api.js:66:9)
at emitNone (events.js:86:13)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
Can anyone explain? I am new to NodeJs. Thanks a lot!
var http = require('http');
var database = require('./database');
var url = require('url');
// Generic find methods (GET)
function findAllResources(resourceName, req, res) {
database.find('OrderBase', resourceName, {}, function (err, resources) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resources));
});
};
var findResourceById = function (resourceName, id, req, res) {
database.find('OrderBase', resourceName, {'_id': id}, function(err, resource) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
});
};
// Generic insert/update methods (POST, PUT)
var insertResource = function (resourceName, resource, req, res) {
database.insert('OrderBase', resourceName, resource, function(err, resource) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
});
};
// Product methods
var findAllProducts = function (req, res) {
findAllResources('Products', req, res);
};
var findProductById = function (id, req, res) {
findResourceById('Products', id, req, res);
};
var insertProduct = function (product, req, res) {
insertResource('OrderBase', 'Product', product, function (err, result) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(result));
});
};
var server = http.createServer(function (req, res) {
// Break down the incoming URL into its components
var parsedURL = url.parse(req.url, true);
// Determine a response based on the URL
switch (parsedURL.pathname) {
case '/api/products':
if (req.method === 'GET') {
// Find and return the product with the given id
if (parsedURL.query.id) {
findProductById(id, req, res);
}
// There is no id specified, return all products
else {
findAllProducts(req, res);
}
}
else if (req.method === 'POST') {
//Extract the data stored in the POST body
var body = '';
req.on('data', function (dataChunk) {
body += dataChunk;
});
req.on('end', function () {
// Done pulling data from the POST body.
// Turn it into JSON and proceed to store it in the database.
var postJSON = JSON.parse(body);
insertProduct(postJSON, req, res);
});
}
break;
default:
res.end('You shall not pass!');
}
});
server.listen(8080);
console.log('Up, running and ready for action!');
database file
// Our primary interface for the MongoDB instance
var MongoClient = require('mongodb').MongoClient;
// Used in order to verify correct return values
var assert = require('assert');
/**
*
* #param databaseName - name of the database we are connecting to
* #param callBack - callback to execute when connection finishes
*/
var connect = function (databaseName, callback) {
// URL to the MongoDB instance we are connecting to
var url = 'mongodb://localhost:27017/' + databaseName;
// Connect to our MongoDB instance, retrieve the selected
// database, and execute a callback on it.
MongoClient.connect(url, function (error, database) {
// Make sure that no error was thrown
assert.equal(null, error);
console.log("Successfully connected to MongoDB instance!");
callback(database);
});
};
/**
* Executes the find() method of the target collection in the
* target database, optionally with a query.
* #param databaseName - name of the database
* #param collectionName - name of the collection
* #param query - optional query parameters for find()
*/
exports.find = function (databaseName, collectionName, query) {
connect(databaseName, function (database) {
// The collection we want to find documents from
var collection = database.collection(collectionName);
// Search the given collection in the given database for
// all documents which match the criteria, convert them to
// an array, and finally execute a callback on them.
collection.find(query).toArray(
// Callback method
function (err, documents) {
// Make sure nothing went wrong
assert.equal(err, null);
// Print all the documents that we found, if any
console.log("MongoDB returned the following documents:");
console.dir(documents);
// Close the database connection to free resources
database.close();
})
})
};

Sailjs-Waterline: Serialize, Parse and initialize an Model

Let's assume that I found user using next command:
User.findOne(id).exec(function(err, user){
redis.set(JSON.stringify(user), id);
})
After that I'm loading from redis my object
redis.get(id, function(err, reply){
if(!err && reply) {
var user = JSON.parse(reply);
// here methods like user.save() or any of defined manually by developer is unavailable
//
} else {
..
}
})
User model example:
module.exports = {
attributes : {
// Simple attribute:
// name: 'STRING',
// Or for more flexibility:
// phoneNumber: {
// type: 'STRING',
// defaultValue: '555-555-5555'
// }
email : {
type: 'string',
unique: true
},
// ...
verifyPass: function(pass, callback) {
var obj = this.toObject();
if (callback) {
return Password.compare(pass, obj.local.password, callback);
}
return Password.compareSync(pass, obj.local.password);
},
// retrieve profile for sending to front end
getProfile: function() {
var obj = this.toObject();
var profile = {};
profile.id = obj.id;
// ...
return profile;
},
I need all of that methods to be work whenever I parse waterline model from json. Is there a way to initialize it without triggering db at all. Also would be nice if I could to call user.save().
There's currently no documented public API for this unfortunately, but you can use,
var user = new PersonCollection._model(values, {showJoins: true});
See how that works for you!