KoaJS server timing out issue - socket.io

I am trying to make a server with KoaJS
//* imports
import Koa from 'koa';
import KoaRouter from 'koa-router';
import KoaStatic from 'koa-static';
import http from 'http';
import sio from 'socket.io';
//* local imports
//* init
const app = new Koa();
const _ = new KoaRouter();
const server = http.createServer(app);
const io = new sio.Server(server);
//* routes
//* io
io.on("connection", async socket => {
console.log("MOMMY I SHIT MYSELF!!");
});
//*listen
app.use(KoaStatic("./public"));
app.use(_.routes());
server.listen(process.env.PORT || 8080, () => {
console.log("listening");
});
but when I go to URL it just never responds.
Any ideas?
Yes. I do have a public/index.html
Yes. It needs to be server.listen

Related

Upload image to server using expo-file-system

In a react native app, I am following the documentation of expo-file-system to upload an image from the gallery of my phone and send it to a node.js server that uses multer to process the file. Unfortunately, I am having the following error when I send the http request:
Possible Unhandled Promise Rejection (id: 1):
Error: Failed to connect to localhost/127.0.0.1:3000
I know that the server is working because I have tested it with the same client but using axios and fetch to send the request and it reached the server.
This is the code that I am using in the client side:
//.env
URL = 'http://localhost:3000/api/upload'
//uploadImage.js
import React, { useState } from "react";
import { View, Button, Image, StyleSheet } from "react-native";
import * as ImagePicker from 'expo-image-picker'
import * as FileSystem from 'expo-file-system';
import {URL} from "#env"
const ImageUpload = ()=>{
const [image, setImage] = useState('')
const [name, setName] = useState('')
const [type, setType] = useState('')
const openImageLibrary = async()=>{
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log('this is the result',result);
if (!result.canceled) {
const uri = result.assets[0].uri
const filename = uri.split('/').pop();
const match = /\.(\w+)$/.exec(filename);
const imageType = match ? `image/${match[1]}` : `image`;
setImage(uri);
setName(filename)
setType(imageType)
}
}
const sendPictureToServer = async()=>{
const response = await FileSystem.uploadAsync(URL ,image,{
fieldName: 'photo',
httpMethod: 'POST',
uploadType: FileSystem.FileSystemUploadType.BINARY_CONTENT,
})
}
return(
<View>
<Button title = 'select' onPress={openImageLibrary}/>
<Button title='send' onPress={sendPictureToServer}/>
</View>
)
}
This is the node.js server
//index.js
const Express = require('express')
const multer = require('multer')
const bodyParser = require('body-parser')
const app = Express()
app.use(bodyParser.json())
const upload = multer({ dest: 'uploads/' } )
app.get('/', (req, res) => {
res.status(200).send('You can post to /api/upload.')
})
app.post('/api/upload', upload.single('photo'), (req, res) => {
console.log('file', req.file)
console.log('body', req.body)
res.status(200).json({
message: 'success!',
})
})
app.listen(3000, () => {
console.log('App running on http://localhost:3000')
})

Apollo graphql subscriptions, using the same endpoint for the graphql server and websocket endpoint

I was just wondering if there was any performance decrease or any disadvantage in using the same endpoint for the graphql endpoint and also for the WebSocket. You can see the sample code below.
import express = require("express");
import { ApolloServer } from "apollo-server-express";
import bodyParser from "body-parser";
import Knex from "knex";
import { execute, subscribe } from "graphql";
import { SubscriptionServer } from "subscriptions-transport-ws";
// graphql api
import api from "./api";
const { createServer } = require("http");
const app: express.Application = express();
const path = "/graphql";
app.use(bodyParser.json());
const graphqlServer = new ApolloServer(api);
graphqlServer.applyMiddleware({ app, path });
const server = createServer(app);
server.listen(process.env.PORT, err => {
if (err) {
throw new Error(err);
}
new SubscriptionServer(
{
execute,
subscribe,
schema: api.schema
},
{
server,
// same as the graphql endpoint
path
}
);
console.log(
`the server is running at http://localhost:${process.env.PORT}/graphql`
);
});

Why is Koa-Pug returning Not Found in included code?

I have the following code...
// File 1
import {Application2} from "./Application2.mjs";
const app = new Application2();
app.start(()=>{
console.log("Application has been started")
});
// File 2
import Koa from "koa";
import Router from "koa-router";
import Pug from "koa-pug";
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const PORT = process.env.PORT || 3001;
export class Application2{
constructor(){
console.log(`This thing ${__dirname}/views`)
this.app = new Koa();
this.pug = new Pug({
app: this.app,
viewPath: `${__dirname}/views`
});
const router = new Router();
router.get("/", function(ctx){
ctx.render('index');
})
this.app.use(router.routes());
}
start(callback){
this.app.listen(PORT, callback);
}
}
When I run this code I see the correct path in the console. However, when I try to go to the site I just see...
I can't figure out why this is happening, can someone help? It seems to match the examples provided here
Ugghhh missed this...
router.get("/", async (ctx) => {
await ctx.render('index');
})
Instead of doing this:
router.get('/', function(ctx){
ctx.render('index')
})
Try This
my_route.get('/', async (body) => {
await body.render('index')
})

Apollo GraphQL - Import .graphql schema as typeDefs

With graphql-yoga you can simply import your schema by doing the following: typeDefs: './src/schema.graphql'. Is there a similar way of doing so with apollo-server-express?
If there isn't, how does one import the typeDefs from an external .graphql file?
I found a way of doing this by using graphql-import which does exactly what I need. See sample code below:
import { ApolloServer } from 'apollo-server-express'
import { importSchema } from 'graphql-import'
import Query from './resolvers/Query'
const typeDefs = importSchema('./src/schema.graphql')
const server = new ApolloServer({
typeDefs,
resolvers: {
Query
}
})
const app = express()
server.applyMiddleware({ app })
app.listen({ port: 4000 })
**
UPDATE: graphql-import v0.7+
**
importSchema is now async and should be handled as a promise. Just wrap it in a async function and simply await it:
async function start() {
const typeDefs = await importSchema(".src/schema.graphql")
}
You can use the function makeExecutableSchema to pass in the typeDefs. Something like this:
import { makeExecutableSchema } from 'graphql-tools';
import mySchema from './src/schema.graphql';
const app = express();
const schema = makeExecutableSchema({
typeDefs: [mySchema],
resolvers: {
...
},
});
app.use(
'/graphql',
graphqlExpress({ schema })
);
As a more recent response, following the top of the tutorial here link one can move the schema to a new file called schema.graphql and then import "fs" and "path" and input in the file so now it looks like:
const fs = require('fs');
const path = require('path');
const server = new ApolloServer({
typeDefs: fs.readFileSync(
path.join(__dirname, 'schema.graphql'),
'utf8'
),
resolvers,
})

error: Response not successful: Received status code 400" Graphql

what i wanted to do is to separate my schema from the index.js file. so here are the index.js file and schema.js file after separation.
//schema.js
import { gql, makeExecutableSchema } from 'apollo-server-express';
const typeDefs = gql`
type Query {
hello : String
}
`;
const resolvers = {
Query:{
hello: () => 'HelloWorld!'
}
};
export default makeExecutableSchema({
typeDefs,
resolvers,
});
//index.js
import { ApolloServer } from 'apollo-server-express';
import express from 'express';
const schema = require('./schema');
const app = express();
const server = new ApolloServer({schema});
server.applyMiddleware({app});
app.listen(4000, ()=> {
console.log(`app is working on port 4000 ${server.graphqlPath}`);
});
i still can open graphql playground on localhost:4000/graphql
but after the separation i receive the following error.
I replaced the line const schema = require('./schema'); to import schema from './schema'; solved my problem.
even though I am using node V8.10 I used the babel compiler to use modern syntax with node. the old syntax was the issue.

Resources