lukeed / polka

A micro web server so fast, it'll make you dance! :dancers:
MIT License
5.43k stars 174 forks source link

Polka/Sapper example with uws #24

Closed ansarizafar closed 6 years ago

ansarizafar commented 6 years ago

Is it possible to use polka/sapper with uws?

lukeed commented 6 years ago

Hey, Polka & Sapper are two separate projects. The example was just to show how to use them together.

But, yes, you can use uws with Polka (and Sapper). There's already an example with uws's HTTP module, but you can definitely attach the socket server too. I have an example for this in the works.

ansarizafar commented 6 years ago

There's already an example with uws's HTTP module

This example is not using Sapper with Polka and uws and I am unable to understand how Polka, uws and Sapper can be used together. Could you please provide an example of using Polka, uws and Sapper together.

Youngestdev commented 6 years ago

There's an example already Check the examples folder and you'll find it.

ansarizafar commented 6 years ago

@Youngestdev There is no such example in examples folder. I am talking about Polka + uws + Sapper example.

Youngestdev commented 6 years ago

@lukeed

lukeed commented 6 years ago

@ansarizafar I actually answered you in Svelte Gitter since you pinged me there. Here's the rough layout, which you could totally piece together from the two examples:

const polka = require('polka');
const { Server } = require('uws');
const sapper = require('sapper')();
const static = require('serve-static')('assets');
const compression = require('compression')({ threshold:0 });

const { PORT=3000 } = process.env;

// (SAPPER) this allows us to do e.g. `fetch('/api/blog')` on the server
const fetch = require('node-fetch');
global.fetch = (url, opts) => {
    if (url[0] === '/') url = `http://localhost:${PORT}${url}`;
    return fetch(url, opts);
};

// Init Polka with Sapper, Compression, and Static Assets middlewares
// grab the `server` key, which is HTTP server
const { server } = polka().use(compression, static, sapper);

// Init uWS Server, using HTTP server
const wss = new Server({ server });

// Do whatever you want with sockets
// You have to connect to them on client-side
wss.on('connection', ws => {
  ws.on('message', msg => {
    console.log('received: %s', msg);
  });
  ws.send('something');
});

// Start listening to HTTP server
server.listen(PORT, _ => {
  console.log(`> Ready on localhost:${PORT}`);
});

For client-side socket listener, you can use native WebSocket or my sockette library.

You have more than enough to finish from here. All this information is easily found in Sapper's, Polka's, and(u)WS's documentations. Just need to look a little bit.

@Youngestdev I already get notifications for everything, no need to ping 😆

Youngestdev commented 6 years ago

Okay !

On Monday, February 5, 2018, Luke Edwards notifications@github.com wrote:

@ansarizafar https://github.com/ansarizafar I actually answered you in Svelte Gitter since you pinged me there. Here's the rough layout, which you could totally piece together from the two examples:

const polka = require('polka');const { Server } = require('uws');const sapper = require('sapper')();const static = require('serve-static')('assets');const compression = require('compression')({ threshold:0 }); const { PORT=3000 } = process.env; // (SAPPER) this allows us to do e.g. fetch('/api/blog') on the serverconst fetch = require('node-fetch');global.fetch = (url, opts) => { if (url[0] === '/') url = http://localhost:${PORT}${url}; return fetch(url, opts); }; // Init Polka with Sapper, Compression, and Static Assets middlewares// grab the server key, which is HTTP serverconst { server } = polka().use(compression, static, sapper); // Init uWS Server, using HTTP serverconst wss = new Server({ server }); // Do whatever you want with sockets// You have to connect to them on client-sidewss.on('connection', ws => { ws.on('message', msg => { console.log('received: %s', msg); }); ws.send('something'); }); // Start listening to HTTP serverserver.listen(PORT, _ => { console.log(> Ready on localhost:${PORT}); });

For client-side socket listener, you can use native WebSocket or my sockette https://github.com/lukeed/sockette library.

You have more than enough to finish from here. All this information is easily found in Sapper's, Polka's, and(u)WS's documentations. Just need to look a little bit.

@Youngestdev https://github.com/youngestdev I already get notifications for everything, no need to ping 😆

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/lukeed/polka/issues/24#issuecomment-363192675, or mute the thread https://github.com/notifications/unsubscribe-auth/Adkrj4ZPkcDxtUkIYZP1Jv21QPti0Q0Sks5tR1T3gaJpZM4R4qEb .

ansarizafar commented 6 years ago

Thanks for the exmaple but I think I was not able to explain my question clearly. I wanted to know, Is it possible to use uws.http server with Polka router/middleware and Sapper. If I understood it correctly, In the above example, we are only using uws socket server to handle websocket request. What I want to achieve is to handle all http requests via uws.http.

lukeed commented 6 years ago

Yes. The example becomes even simpler and you can use the with-uws example directly.

ansarizafar commented 6 years ago

uws example in this repo only shows how to handle a single route. My question is how can we handle all sapper routes via uws.http server.

lukeed commented 6 years ago

It's the exact same thing man, you'll get it.

ansarizafar commented 6 years ago

I don't think its the same thing. I am not an expert, but in my opinion It will only be possible If we somehow can replace polka's http server with uws.http server. Anyways thanks for the reply.

lukeed commented 6 years ago

Look at https://github.com/lukeed/polka/blob/master/examples/with-https/index.js

Define your Polka app, with routing.

Create the UWS HTTP server, passing Polka's handler to it.

You can do this for any custom HTTP server, that's what both the UWS & HTTPS examples are showing.

ansarizafar commented 6 years ago

https example shows a single handler for all routes. and uws example shows how to pass that handler to uws.http server. The handler will always return POLKA: Hello from ${req.pathname} for all routes. What about Sapper routes? How sapper routes will work with this code

polka().use(compression, static, sapper);

const { handler } = polka().get('*', (req, res) => {
    res.end(`POLKA: Hello from ${req.pathname}`);
});

http.createServer(handler).listen(PORT, err => {
    console.log(`> Running on localhost:${PORT}`);
});
lukeed commented 6 years ago

Yes... The Polka app is a single handler, but use whatever routing you want to use. It's a simple example.

I'm guessing you have not read the documentation, or used Express in the past.

I'm going to use the longer, more terse format so that you can see everything more clearly.

const polka = require('polka');
const { http } = require('uws');

const { PORT=3000 } = process.env;

const app = polka();

// attach middleware
app.use(compression, static, sapper);

// attach any routes
app.get('/api/users', (req, res) => { ... });
app.post('/api/users', (req, res) => { ... });
app.get('/api/users/:id', (req, res) => { ... });
app.put('/api/users/:id', (req, res) => { ... });
app.delete('/api/users/:id', (req, res) => { ... });

// create UWS HTTP server
// ~> pass it Polka's ROUTE HANDLER
http.createServer(app.handler).listen(PORT, err => {
  console.log(`> Running on localhost:${PORT}`);
});

This is all the help I'll offer you & it's far more than I probably should have given. Of course I'm happy to help, but you have to have tried to help yourself first.

Lastly, you should work with native http module first, so that you learn. UWS's http is intentionally incomplete & there are probably missing methods or bugs that you won't expect. Twice the speed is nice, but it's meaningless if you don't understand what it's doing & don't have a solid foundation for figuring out what happens when/if it breaks.

Good luck~! 🙌

ansarizafar commented 6 years ago

As I mentioned before I am not an expert but I have used express in the past and now a days I am using my own fastify like framework build on top of native http and router module and graphql inspired data layer with single endpoint and request batching support and my own front end framework build on top of hyperhtml with global store mangement via javascript proxies. I have tried to use uws.http many times in the past without any success because (as you correctly mentioned) UWS's http is intentionally incomplete & there are probably missing methods or bugs. After I saw uws.http example I was wondering How its working with polka and sapper. Thanks for complete example and detailed explanation. I also Thank you for Polka and all your opensource work.

lukeed commented 6 years ago

Cool! It sounds like you have a good start then.

Good luck with your project, and with revitalizing your nifty stack 🎉

talentlessguy commented 3 years ago

Pardon for writing on such an old issue but uws is deprecated as of now.

A better way would be using ws:

import http from 'http'
import polka from 'polka'
import WebSocket from 'ws'

const server = http.createServer()

polka({ server }).listen(3000, (err) => {
  if (err != null) throw err
  console.log(`Running on http://localhost:3000`)
})

const wss = new WebSocket.Server({ server })

wss.on('connection', (socket) => {
  socket.on('message', () => { /* ... * / }))
})