Currently my code looks like this:
module Nexus {
export class Scraper {
private summonerName: string;
private apiKey: string = '';
private summonerStatsUrl = '';
constructor(name: string) {
this.summonerName = name;
}
getSeasonRank(): string {
return 'aa';
}
getRankedStats(): string {
return 'aa';
}
getSummonerStats(callback: Function) {
var summonerStats = request(this.summonerStatsUrl + this.apiKey, function (error, body, response) {
callback(response);
});
}
}
}
And app.ts:
///<reference path="./Nexus.ts"/>
var colors = require('colors'),
request = require('request'),
fs = require('fs'),
readline = require('readline'),
rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Insert summoner name: \r\n >> ', function (answer) {
var scraper = new Nexus.Scraper(answer);
scraper.getSummonerStats(function (result) {
console.log(result);
});
});
When I reach the new Nexus.Scraper(), I'm getting this error:
Nexus is not defined
While it should be since I'm including it? The module is named Nexus and I'm exporting the Scraper class. (The file is called Nexus.ts.)
Make sure your module looks as follows:
module Nexus {
export class Scraper {
private summonerName: string;
private apiKey: string = '';
private summonerStatsUrl = '';
constructor(name: string) {
this.summonerName = name;
}
getSeasonRank(): string {
return 'aa';
}
getRankedStats(): string {
return 'aa';
}
getSummonerStats(callback: Function) {
var summonerStats = request(this.summonerStatsUrl + this.apiKey, function (error, body, response) {
callback(response);
});
}
}
}
export = Nexus;
Then, rather than using /// <reference /> do this:
import Nexus = require('Nexus');
You also need to export the module
export module Nexus {
...
}
then in your app.ts you can call it like:
import Nexus = require('./Nexus.ts');
Related
import { Inject, Injectable } from "#nestjs/common";
import { DocumentClient } from "aws-sdk/clients/dynamodb";
export class Service {
constructor(
#Inject(DYNAMODB_TOKEN) private readonly dynamodbClient: DocumentClient,
) {
this.logger.setContext(Service.name);
}
async findRecords(itemId: string): Promise<any> {
const method_name = "findRecordsById";
this.logger.info(`Retrieving DlqRecords for the uuid: ${itemId}`);
var output: any = "";
try {
var result = this.dynamodbClient.get({ TableName: this.DLQ_TABLE, Key: { id: itemId } }).promise();
result.then(res=>{output=res.Item?res.Item:"not found"}).catch(err=>console.log(err));
} catch (error) {
console.log(
`Method Name: ${method_name} and UUID: ${itemId}: Find DLQ records failed with exception`
);
}
return output;
}
}
I am not able to retrieve the record from Dyanmo DB in nest JS project. Tried below way to retrieve the records.
aws-sdk dependency version : "^2.1282.0"
npm version: 8.19.1 node: v18.9.0
Using getItem(). It did not gave any error however it didn't go neither inside if(err) nor else block and output was undefined.
You created a variable called inputParams but pass params to your API call getItem(params). Try use getItem(inputParams)
If that fails try this:
var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});
var dynamodb = new AWS.DynamoDB();
var inputParams = {
TableName: this.DLQ_TABLE,
Key: {
"id" : {"S": itemId}
}
};
var result = await dynamodb.getItem(inputParams).promise()
result.then(res=>{output=res.Item?res.Item:"not found"}).catch(err=>console.log(err))
return output
Edit Doc client example
import { DocumentClient } from 'aws-sdk/clients/dynamodb'
const ddb = new DocumentClient()
const TableName = this.DLQ_TABLE
const Key = {
"id" : itemId
}
await ddb
.get({
TableName,
Key,
})
.promise()
Can I not make a class that extends this DataRepository class below and access the key/value inside its JSON file?
const fs = require("fs");
class DataRepository {
constructor(filename) {
if (!filename) {
throw new Error("Creating a repository requires a filename");
}
this.filename = filename;
try {
fs.accessSync(this.filename);
} catch (error) {
console.error("data does not exist");
}
}
async getAll() {
// Open the file called this.filename
return JSON.parse(
await fs.promises.readFile(this.filename, {
encoding: "utf-8",
})
);
}
async getOneBy(filters) {
const records = await this.getAll();
for (let record of records) {
let found = true;
for (let key in filters) {
if (record[key] !== filters[key]) {
found = false;
}
}
if (found) {
return record;
}
}
}
}
module.exports = new DataRepository("cales_data.json");
This is what I was trying when I got this error:
const fs = require("fs");
const DataRepository = require("./repositories/data");
class Address extends DataRepository {
constructor() {
this.Address = DataRepository.Address;
this.Latitude = DataRepository.Latitude;
this.Longitude = DataRepository.Longitude;
}
}
At the end of the day, I have a json file that is an array of objects that looks like this:
{
'Number (original project order)': 99,
FIELD2: null,
Code_Notes: 'Not enough room to code historic preservation approval body',
'Filler column to reference original sheet': '402 W Santa Clara St',
City: 15,
Planning_ID: 'PDC15-051',
APN: '25938036',
Total_Number_Parcels: -888,
Address: '402 W Santa Clara St',
Description_from_Agenda: 'A Planned Development Permit to allow the construction of a mixed use development with up to 1.04 million square feet for office/retail and up to 325 multi-family attached residences on a 8.93 gross acre site. ',
Census_Tract: '5008.00',
Council_District: '3',
Neighborhood_Planning_Group: '-999',
Community_Plan_Area: '-999',
Specific_Plan_Area: 'Downtown',
General_Plan_Designation: 'Downtown',
I would like to be able to access its properties via JavaScript classes.
As georg already pointed out, you need to export the class itself in order to extend it.
module.exports = DataRepository;
Since you seem to want to set a filename, but that filename is hard-coded in the module anyways, you can just set that in the constructor.
class DataRepository {
constructor() {
this.filename = "cales_data.json";
try {
fs.accessSync(this.filename);
} catch (error) {
console.error("data does not exist");
}
}
...
I created a base class that parses a json file:
const fs = require("fs");
class DataRepository {
constructor() {
this.filename = "cales_data.json";
try {
fs.accessSync(this.filename);
} catch (error) {
console.error("data does not exist");
}
}
async getAll() {
// Open the file called this.filename
return JSON.parse(
await fs.promises.readFile(this.filename, {
encoding: "utf-8",
})
);
}
async getOneBy(filters) {
const records = await this.getAll();
for (let record of records) {
let found = true;
for (let key in filters) {
if (record[key] !== filters[key]) {
found = false;
}
}
if (found) {
return record;
}
}
}
}
module.exports = DataRepository;
I don't care for its methods at this point. I just want to be able to access the contents of this.filename = "cales_data.json";
Something like this perhaps:
const DataRepository = require("./repositories/data");
class Address extends DataRepository {
constructor() {
super();
this.Address = DataRepository.Address;
this.Latitude = DataRepository.Latitude;
this.Longitude = DataRepository.Longitude;
}
}
module.exports = Address;
but obviously the above gives me undefined. Is it possible to access those properties inside that JSON file in that base class this way? If so, how?
Simple answer: no. "This" can never result to anything than a value on the class memory stack. You have to handle this different:-)
I'm new to angular and I'm trying to create a download link upon button click that downloads doc file. The file gets downloaded successfully but the content inside is something else which is '[object Object]'. The file path is in my webroot and I'm accessing the file like this:
[Route("api/[Controller]")]
[ApiController]
public class DownloadController : Controller
{
private readonly IWebHostEnvironment _env;
public DownloadController(IWebHostEnvironment env)
{
_env = env;
}
[HttpGet]
public async Task<IActionResult> Download()
{
string filePath = Path.Combine(_env.WebRootPath, "Image\\CV.doc");
using MemoryStream memorystream = new MemoryStream();
using (var stream = new FileStream(filePath, FileMode.Open))
{
await stream.CopyToAsync(memorystream);
}
memorystream.Position = 0;
return File(memorystream, "application/msword", "CV.doc");
}
}
my Shared service.ts. I've changed the observe to 'body' as well.
import { Injectable } from '#angular/core';
import { HttpClient, HttpResponse } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class SharedService {
cvFilePathURL = "https://localhost:44346/api/Download";
constructor(private http: HttpClient) { }
getCV(): Observable<any> {
return this.http.get(this.cvFilePathURL, {
observe: 'response',
responseType: 'text'
});
}
}
and this is my componenet.ts
import { Component } from '#angular/core';
import { SharedService } from 'src/app/shared.service';
#Component({
selector: 'app-nav-menu',
templateUrl: './nav-menu.component.html',
styleUrls: ['./nav-menu.component.css']
})
export class NavMenuComponent {
constructor(private service: SharedService) { }
isExpanded = false;
collapse() {
this.isExpanded = false;
}
toggle() {
this.isExpanded = !this.isExpanded;
}
public Download(): void {
this.service.getCV().subscribe((data) => {
var newBlob = new Blob([data], { type: "application/msword" });
//For Internet Explorer
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
return window.navigator.msSaveOrOpenBlob(newBlob);
}
//For other browsers:
//Create a link pointing to the ObjectURL containing the blob.
const mainData = window.URL.createObjectURL(newBlob);
var link = document.createElement('a');
link.href = mainData;
link.download = "CV.doc";
link.click();;
});
}
}
target framework - asp.net core 3.1
Angular Cli - 11.0.6
Update:
So I've managed to download file which has actual contents other than [objects Objects]. However, The file is filled with special characters and is 206 pages long. Original document is only 2 pages long.
I think there are some changes you might have to do inside your code or you can check my code what I am going to provide below.
YOU CONTROLLER
[HttpPost]
[Route("get-download-file")]
public HttpResponseMessage GetDownloadFile(dynamic data)
{
// var localFilePath = HttpContext.Current.Server.MapPath("~/Documents/" + (string)data.fileName);
var localFilePath = HttpContext.Current.Server.MapPath((string)data.mappingPath);
string contentType = MimeMapping.GetMimeMapping(Path.GetExtension(localFilePath));
HttpResponseMessage response = null;
try
{
if (!File.Exists(localFilePath))
{
//if file not found than return response as resource not present
response = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
//if file present than read file
var fStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read);
//compose response and include file as content in it
response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StreamContent(fStream)
};
//set content header of reponse as file attached in reponse
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(fStream.Name)
};
//set the content header content type as application/octet-stream as it returning file as reponse
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
}
}
catch (Exception ex)
{
return response;
}
return response;
}
In your Service(Angular) add that httpPostMethod:
public httpPostFile(url: string, body: any): Observable<Blob> {
return this.httpClient.post<Blob>(this.baseUri + url, body, { responseType: 'blob' as 'json' })
.pipe(
catchError(this.handleClientError)
);
}
Finally, you have to call that method from angular. Using code below->
let tempBlob: any;
let contentFileType= 'txt'; //you can make that file type dynamic using some addional code.
const data = {
fileName: this.fileName,
mappingPath: '~/Documents/' + this.fileName
};
this.apiService.httpPostFile('download/get-download-file/', data)
.subscribe(fileData => {
tempBlob = new Blob([fileData], { type: contentFileType });
},
(error) => {
}, () => {
const blob: Blob = new Blob(tempBlob, { type: contentFileType });
const fileName: string = this.filedlName;
const objectUrl: string = URL.createObjectURL(blob);
const a: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;
a.href = objectUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(objectUrl);
});
Note: There can be more efficient way to download a file in angular and ASP MVC Web API. But this way it worked for me. you can try it. If you find any difficulties than feel free to ask. Thank you.
Im trying to extend a Mongoose Model using ES6 syntax. While I can call successfully find({}) to retrieve data from mongo database, I am not able to call save() to save data. Both are executed inside the Model.
The error returned is Error: TypeError: this.save is not a function
const mongoose = require('mongoose')
const {Schema, Model} = mongoose
const PersonSchema = new Schema(
{
name: { type: String, required: true, maxlength: 1000 }
},
{ timestamps: { createdAt: 'created_at', updatedAt: 'update_at' } }
)
class PersonClass extends Model {
static getAll() {
return this.find({})
}
static insert(name) {
this.name = 'testName'
return this.save()
}
}
PersonSchema.loadClass(PersonClass);
let Person = mongoose.model('Persons', PersonSchema); // is this even necessary?
(async () => {
try {
let result = await Person.getAll() // Works!
console.log(result)
let result2 = await Person.insert() // FAILS
console.log(result2)
} catch (err) {
throw new Error(err)
}
})()
Im using:
Nodejs 7.10
mongoose 5.3.15
This is normal. You're trying to access a non static method from a static method.
You need to do something like this:
static insert(name) {
const instance = new this();
instance.name = 'testName'
return instance.save()
}
Some working example:
class Model {
save(){
console.log("saving...");
return this;
}
}
class SomeModel extends Model {
static insert(name){
const instance = new this();
instance.name = name;
return instance.save();
}
}
const res = SomeModel.insert("some name");
console.log(res.name);
Here is an example of what works and what doesn't work.
class SomeParentClass {
static saveStatic(){
console.log("static saving...");
}
save(){
console.log("saving...");
}
}
class SomeClass extends SomeParentClass {
static funcStatic(){
this.saveStatic();
}
func(){
this.save();
}
static funcStaticFail(){
this.save();
}
}
//works
SomeClass.funcStatic();
//works
const sc = new SomeClass();
sc.func();
//fails.. this is what you're trying to do.
SomeClass.funcStaticFail();