How to use mysql2 library with Sapper? - node.js

I am creating an application in Svelte Sapper. I have a routes/account/login.js API route where I am trying to use mysql2. The route itself works (I checked with Postman), but as soon as I import mysql, the server crashes and an error appears:
[rollup-plugin-svelte] The following packages did not export their `package.json` file so we could not check the "svelte" field. If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.
- mysql2
import mysql from "mysql2/promise";
export async function post(req, res) {
//route test
const { login, password } = req.body;
res.end(`${login}, ${password}`);
}
What can I do to make this import work?
What can I do to make this import work?
The Sapper documentation doesn't say anything about whether you need to change something in the configuration additionally. https://sapper.svelte.dev/docs#Server_routes

I found a solution. I had to create a #lib folder in the src/node_modules folder and there file eg. db.js. In that file instead of import you need to use require()! and then you have to export the function that connects to the database. and then you can import that in the path
//src/node_modules/#lib/db.js
const mysql = require("mysql2");
export async function connectToDatabase() {
return mysql.createConnection({
host: "localhost",
....
})
}
//routes/account/login.js
import { query } from "#lib/db";
export async function post(req, res) {
...
}

Related

Use TypeORM repository or method on a service from outside any module

I have a nestjs app that has an AuthService which has these parts:
export class AuthService {
constructor(
#InjectRepository(User)
private readonly userRepo: Repository<User>,
) {}
async updateFromInternally () {
...
}
I have another file which is, crucially, outside of any module, which contains a number of helpful functions relating to Google oauth. For example, this file initiates Google's oauth2 client like so:
export const oauth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_CLIENT_REDIRECT
);
This file also has a listener function which I found in Google's documentation as a way to catch when my use of Google's oauth2 client automatically uses a refresh token to obtain a new access token:
oauth2Client.on('tokens', async (tokens) => {
[****]
})
At [****], I need to query in my database for a particular user and update them. Either of these conceptually work:
I somehow get userRepo into this file right here and use it to query + update
I somehow call updateFromInternally in AuthService from here
But I don't know how to interact with either TypeORM repositories or methods within services from outside of any module in nestjs! Can I do either of these?
The first question is why you're using nestjs?
You can access the internals of nestjs by using the instantiated app;
In your main.ts file you have something like this:
const app = await NestFactory.create(AppModule);
You can access the services or DataSource from the app by using the get method.
import {DataSource} from 'typeorm'
const dataSource = app.get<DataSource>(DataSource)
// or custom service
const someServices = app.get<SomeService>(SomeService)
you just need a way to export app from main.ts and import it in your outside world.
for example:
// main.ts
let app;
async bootstrap() {
app = await NestFactory.create(AppModule);
}
export const getApp = () => app;
bootstrap()
and in your other file
// outside.ts
import {getApp} from './main.ts'
const app = getApp()
I didn't write the whole logic, but I think it would give you an idea of what you need to do.
But in my opinion, it's the worst thing you can do. You're using 'nestjs` and try to respect its philosophy.
Just write a module that handles all the work you want.
I figured out #1:
import {getRepository} from "typeorm";
oauth2Client.on('tokens', async (tokens) => {
const gaRepo = getRepository(Googleauth);
// Can now use gaRepo like you do in a service
})

Add custom header when create new remote database with pouchdb

I'm testing to send custom headers when creating a remote database with PouchDB. The fact is that according to the documentation the way to proceed is as follows (https://pouchdb.com/api.html):
var db = new PouchDB('http://example.com/dbname', {
fetch: function (url, opts) {
opts.headers.set('X-Some-Special-Header', 'foo');
return PouchDB.fetch(url, opts);
}
});
My code is almost copied and pasted
const db = new PouchDB(this.server, {
fetch(url, opts) {
opts.headers.set('xx-custom-xx', this.text);
opts.credentials = 'include';
return PouchDB.fetch(url, opts);
}
});
When I try to launch it I get two errors:
Error1: "export 'fetch' (imported as 'PouchDB') was not found in 'pouchdb' (possible exports: default)" This error is being given by the line"return PouchDB.fetch(url, opts); "
Error2: "set does not exist on type headersinit"
I hope someone can help me. Thanks.
I get it.. the problem are two.
First, I was importing Pouch like this
import * as PouchDB from 'pouchdb';
I have notice in other project I imported it by
import PouchDB from 'pouchdb';
In my new project with import PouchDB from 'pouchdb'; didn't work because I didn't set "allowSyntheticDefaultImports":true flag in tsconfig
AllowSyntheticDefaultImports flag is specified in doc but It does't work (no for me) with import * as PouchDB from 'pouchdb';

App Object in Electron Module and getAppPath throws Error

I have a strange problem with my application. I get an error, and I can't solve it. First at all, I installed a new project, so everything is clean. Someone sent me this repo to use for an Angular, Electron and Nodejs Application. Everything worked fine, but then I decided to install an embedded database like sqlite3. For this I found NeDB, and the module is perfect for my needs. First I had the problem, has nothing to do with my general problem, that I can't create a database file. So I read that I can only create files in my application path, because something about Electron and that's working in a browser.
I found the getAppPath() method that is implemented in my app object from the Electron module. Here starts the problem. For hours I tried to get the application path from this object. Finally, I wrote this code.
import { Injectable } from '#angular/core';
var nedb = require('nedb');
import { app } from 'electron';
import * as path from 'path';
#Injectable()
export class DatabaseService {
app: typeof app;
Database: any;
constructor() {
this.app = window.require("electron").app;
this.Database = new nedb({ filename: path.join(this.app.getAppPath(), '/diary.db'), autoload: true, timestampData: true });
var scott = {
name: 'Scott',
twitter: '#ScottWRobinson'
};
this.Database.insert(scott, function(err, doc) {
console.log('Inserted', doc.name, 'with ID', doc._id);
});
}
}
And I get this error.
I found this posting, but I don't really understand what the post is trying to tell me. I followed the links, but nothing seems to help. Anyone have an idea?

How to import a default export of webpack entry file from outside?

I think I can best explain it with code. I have a file in webpack like the following:
import ReactDOMServer from 'react-dom/server';
import Server from './server';
import templateFn from './template';
export default (req, res) => {
const reactString = ReactDOMServer.renderToString(<Server />);
const template = templateFn(html);
res.send(template);
};
I also have an express application where I want to have access to the default exported function. If it makes any difference, this file is the webpack entry file. Here is what I tried in my express app:
const handleRequest = require(path.resolve(webpackConfig.output.path, webpackConfig.output.filename));
app.get('*', (req, res) => {
console.log(handleRequest);
});
I was trying to import the webpack generated file with the hope that I will be able to access the entry file's default export. Well, I was wrong as the output of the import was {}.
Is there a webpack plugin or some kind of a technique to do what I am trying to build? I don't want the express application to be part of the webpack build. That was the main reason I separated the code in this way.
I was able to access contents of webpack using library parameter (webpack.config.js):
output: {
path: ...,
filename: ...,
library: 'myapp',
libraryTarget: 'commonjs'
}
Then access it in the code:
const output = require(path.resolve(webpackConfig.output.path, webpackConfig.output.filename));
const defaultExportFunction = output.myapp.default;

Router is not defined in KOA2

I have two files, one of them is the app.js and the otherone is api.js.
In the first file I have :
app.use(setHeader)
app.use(api.routes())
app.use(api.allowedMethods())
And in api.js I have:
import KoaRouter from 'koa-router';
const api = new Router();
//Validatekey
const validateKey = async (ctx, next) => {
const { authorization } = ctx.request.headers;
console.log(authorization);
if (authorization !== ctx.state.authorizationHeader) {
return ctx.throw(401);
}
await next();
}
api.get('/pets', validateKey, pets.list);
When I run the project a error message is throw: Router is not defined.
But If I write both files together, the application go fine.
Anybody knows the problem?
I have solved with var Router = require('koa-router')
The import is currently not implemented in nodejs, neither is it supported in the latest ES2015(ES6).
You will need to use a transpiler like Babel to use import in code.I advice that avoid transpiler as it cause performance issues on production just go with require and it will work.
Obviously Nodejs does not support import / export syntax and using require will solve your problem.
However it is possible to make import work on Node.js by using babel transformers.
Look the following answer for more information https://stackoverflow.com/a/37601577/972240

Resources