Django Channels + nuxt-socket-io not working - websocket

I'm developing an app using Django as the backend framework and Vuex + Nuxt in the client-side. I tried to integrate websockets by using django-channels and nuxt-socket-io.
I cannot connect both libraries because django is exposing the websocket's urls with ws protocol (e.g. ws://localhost:8000/ws/roomName) and nuxt-socket-io library looks for the conection with http protocol. How can nuxt-socket-io library be configured to work with ws protocol or serve the django channels in the http protocol?
I leave here some of the main files that can be interesting to understand the configuration
asgi.py
import logging
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from django.urls import re_path
from apps.websockets.consumers import UserWebsocketConsumer
logger = logging.getLogger(__name__)
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter([
re_path('ws/', UserWebsocketConsumer.as_asgi())
])
),
})
nuxt.config
modules: [
'#nuxtjs/style-resources',
'#nuxtjs/axios',
'#nuxtjs/auth-next',
'#nuxtjs/dotenv',
//process.env.NODE_ENV === 'production' ? '#nuxtjs/sentry' : ''
'#nuxtjs/sentry',
['#nuxtjs/i18n',
{
strategy: 'no_prefix',
locales: [
{ name: 'Español', code: 'es', iso: 'es-ES', file: 'es.js' },
//{ name: 'English', code: 'en', iso: 'en-US', file: 'en.js' },
{ name: 'Català', code: 'ca', iso: 'ca-ES', file: 'ca.js' },
//{ name: 'Code', code: 'code', iso: 'code', file: 'code.js' },
],
//lazy: true,
langDir: "i18n/",
defaultLocale: process.env.DEFAULT_LANG || 'es',
baseUrl: process.env.PUBLIC_URL,
//detectBrowserLanguage: false,
detectBrowserLanguage: {
useCookie: true,
cookieKey: 'django_language',
redirectOn: 'root', // recommended
},
vueI18n: {
fallbackLocale: "es"
}
}
],
'nuxt-socket-io'
],
io: {
sockets: [
{
name: 'django-backend',
url: `ws://localhost:8000`,
default: true
}
],
If you need more details about some file or version of the libraries let me know

Related

postcss-url not generating base64 url

I am building a library which is used as a package in a Next.js app.
I have a variable in my .scss file which uses an url('./some-file.png') and I want this to generate a base64 url in order to be used in my other app easily.
When I build the project, after adding postcss-url, the generated url has not changed...there is no base64 url generated.
rollup.config.js:
import peerDepsExternal from 'rollup-plugin-peer-deps-external'
import resolve from '#rollup/plugin-node-resolve'
import commonjs from '#rollup/plugin-commonjs'
import typescript from '#rollup/plugin-typescript'
import postcss from 'rollup-plugin-postcss'
import copy from 'rollup-plugin-copy'
import svgr from '#svgr/rollup'
import dts from 'rollup-plugin-dts'
import del from 'rollup-plugin-delete'
import analyze from 'rollup-plugin-analyzer'
import { terser } from 'rollup-plugin-terser'
import json from '#rollup/plugin-json'
import graphql from '#rollup/plugin-graphql'
import fs from 'fs'
import url from 'postcss-url'
import path from 'path'
import * as packageJson from './package.json'
const tsConfig = JSON.parse(fs.readFileSync(__dirname + '/tsconfig.json', 'utf8'))
export default [
{
input: 'src/index.ts',
output: [
{
file: packageJson.main,
format: 'cjs',
sourcemap: true
},
{
file: packageJson.module,
format: 'esm',
sourcemap: true
}
],
plugins: [
peerDepsExternal(),
copy({
targets: [
{
src: [
'src/ui/styles/palette.scss',
'src/ui/styles/themes.scss',
'src/ui/styles/urls.scss',
'src/ui/styles/_exports.module.scss'
],
dest: 'lib/scss'
},
{ src: 'src/assets/images', dest: 'lib/assets' }
],
verbose: true
}),
svgr({ dimensions: false }),
resolve({ preferBuiltins: true, mainFields: ['browser'] }),
postcss({
plugins: [
url({
url: "inline"
}),
],
extract: path.resolve('lib/styles.scss'),
}),
commonjs(),
json(),
typescript({ tsconfig: './tsconfig.json' }),
graphql(),
terser(),
analyze({ summaryOnly: true })
]
},
{
input: 'lib/types/src/index.d.ts',
output: [{ file: 'lib/index.d.ts', format: 'esm' }],
external: [/\.scss$/],
plugins: [
dts({
compilerOptions: {
baseUrl: '.',
paths: tsConfig.compilerOptions.paths
}
}),
del({ hook: 'buildEnd', targets: './lib/types' })
]
}
]
button.scss
#import '../../styles/themes.scss';
.background-color-header {
background: themed('header-background');
}
themes.scss
#import './urls.scss';
header-background: url($light-url) no-repeat #{','} $gradient-light-background-header,
and finally : urls.scss
$light-url: '/assets/images/my-image.png';
styles.scss which is the result of the build:
.background-color-header {
background: url("/assets/images/my-image.png") no-repeat , transparent linear-gradient(180deg, #faf8f4 0%, white 100%) 0% 0% no-repeat padding-box;
}
So, you can see that the url is not base64 ...
Any advice?

Routing in Serverless nuxt app not working

So I'm getting a routing problem whenever I use nuxt ssr with serverless. When I use either deploy to AWS lambda or use serverless-offline it generates the url prefixed with /{stage}, but nuxt can't seem to handle this and either throws 403, 404 or 500 errors because the routes to static files aren't prefixed with /{stage}.
I have tried adding {stage} to the public path on build, the results in a 404 because now the static file path needs to prefixed with another /{stage}. If I go directly to {stage}/{stage}/_nuxt/{file} it works.
build: {
publicPath: '/{stage}/_nuxt'
}
So looking around I found that I can update the router base to the below
router: {
base: '/{stage}'
}
but now the file only loads if its {stage}/{stage}/{stage}/_nuxt/{file} and removing the publicPath code above doesn't make it work either.
And this is for the static files, when it comes to the actual routes the homepage set at '/' either works but any other pages don't because the nuxt-links to them aren't prefixed with /{stage} or if I add the prefix to the base I get a Cannot GET / error when I visit /{stage}.
I have tried many different ways of doing this such as using express however I have had no luck and any tutorials that I found online are at least 2 years old and the github repos have the same problem. The closest thing I have found on stackoverflow that is somewhat similar to what I have is here but this is for a static site.
Anybody have any ideas? Below is the code for the serverless.yaml, handler.js, nuxt.js, nuxt.config.js.
Github Repo
serverless.yaml
service: nuxt-ssr-lambda
provider:
name: aws
runtime: nodejs12.x
stage: ${env:STAGE}
region: eu-west-1
lambdaHashingVersion: 20201221
environment:
NODE_ENV: ${env:STAGE}
apiGateway:
shouldStartNameWithService: true
functions:
nuxt:
handler: handler.nuxt
events:
- http: ANY /
- http: ANY /{proxy+}
plugins:
- serverless-apigw-binary
- serverless-dotenv-plugin
- serverless-offline
custom:
apigwBinary:
types:
- '*/*'
handler.js
const sls = require('serverless-http')
const binaryMimeTypes = require('./binaryMimeTypes')
const nuxt = require('./nuxt')
module.exports.nuxt = sls(nuxt, {
binary: binaryMimeTypes
})
nuxt.js
const { Nuxt } = require('nuxt')
const config = require('./nuxt.config.js')
const nuxt = new Nuxt({ ...config, dev: false })
module.exports = (req, res) =>
nuxt.ready().then(() => nuxt.server.app(req, res))
nuxt.config.js
module.exports = {
telemetry: false,
head: {
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
css: [
],
plugins: [
],
components: true,
buildModules: [
'#nuxtjs/tailwindcss',
],
modules: [
],
router: {
base: '/prod'
},
build: {
}
}
Are you passing it as
<p>Path: {{ $route.path }}</p>
<NuxtLink to="/">Back to Mountains</NuxtLink>
if Yes then it should work else try going with redirect('/{stage}/_nuxt')
for an if statement put this inside else , I think it should work.

Rollup CommonJS plugin throwing error when importing Sass files in dependencies

I'm using Rollup on a Sapper project found here: https://github.com/darryl-snow/perfect-cookie
Yesterday I ran npm update and since then when I run npm run dev I get the following error:
✗ client
Invalid CSS after "...-features: list": expected expression (e.g. 1px, bold), was ".append($available-"
✗ server
Invalid CSS after "...-features: list": expected expression (e.g. 1px, bold), was ".append($available-"
internal/modules/cjs/loader.js:985
throw err;
^
My rollup config:
import resolve from '#rollup/plugin-node-resolve'
import replace from '#rollup/plugin-replace'
import commonjs from '#rollup/plugin-commonjs'
import svelte from 'rollup-plugin-svelte'
import postcss from 'rollup-plugin-postcss'
import babel from 'rollup-plugin-babel'
import { terser } from 'rollup-plugin-terser'
import config from 'sapper/config/rollup.js'
import pkg from './package.json'
const mode = process.env.NODE_ENV
const dev = mode === 'development'
const legacy = !!process.env.SAPPER_LEGACY_BUILD
const onwarn = (warning, onwarn) =>
(warning.code === 'CIRCULAR_DEPENDENCY' && /[/\\]#sapper[/\\]/.test(warning.message)) || onwarn(warning)
const postcssOptions = () => ({
extensions: ['.scss', '.sass'],
extract: false,
minimize: true,
use: [
[
'sass',
{
includePaths: ['./src/theme', './node_modules'],
},
],
],
})
export default {
client: {
input: config.client.input(),
output: config.client.output(),
plugins: [
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode),
}),
svelte({
dev,
hydratable: true,
emitCss: true,
}),
resolve({
browser: true,
dedupe: ['svelte'],
}),
commonjs(),
postcss(postcssOptions()),
legacy &&
babel({
extensions: ['.js', '.mjs', '.html', '.svelte'],
runtimeHelpers: true,
exclude: ['node_modules/#babel/**'],
presets: [
[
'#babel/preset-env',
{
targets: '> 0.25%, not dead',
},
],
],
plugins: [
'#babel/plugin-syntax-dynamic-import',
[
'#babel/plugin-transform-runtime',
{
useESModules: true,
},
],
],
}),
!dev &&
terser({
module: true,
}),
],
onwarn,
},
server: {
input: config.server.input(),
output: config.server.output(),
plugins: [
replace({
'process.browser': false,
'process.env.NODE_ENV': JSON.stringify(mode),
}),
svelte({
generate: 'ssr',
dev,
}),
resolve({
dedupe: ['svelte'],
}),
commonjs(),
postcss(postcssOptions()),
],
external: Object.keys(pkg.dependencies).concat(
require('module').builtinModules || Object.keys(process.binding('natives'))
),
onwarn,
},
serviceworker: {
input: config.serviceworker.input(),
output: config.serviceworker.output(),
plugins: [
resolve(),
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode),
}),
commonjs(),
!dev && terser(),
],
onwarn,
},
}
I've tried rm -rf ./node_modules && npm install but still getting the same error. It looks like commonJS is loading dependencies and finding one where it's expecting CSS but getting Sass... I'm completely new to rollup, any ideas?
You should probably consider installing the latest major version of #rollup/plugin-commonjs. The one you're currently using has a bug with Sapper (which I've encountered while running your repo instead of the one in the question) and it was fixed in the later versions.
After upgrading that, your project seems to start up fine.
While you're at it, upgrade the other major version upgrades, very likely that most of them will go by without errors.

Why lazyload is not working on submodules?

I have a little question , i try to customize my router for lazy load Angular CLI 8 , if i try to put loadChildren on sub modules i have some errors.
app.routing.ts
import { CommonModule, } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { Routes, RouterModule } from '#angular/router';
import { LoginComponent } from './login/login.component';
import {CoreComponent} from './core/core.component';
const routes: Routes = [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full',
},
{
path: 'login',
component: LoginComponent
},
{
path: '',
component: CoreComponent,
children: [
{
path: '',
loadChildren: () => import('./core/core.module').then(mod => mod.CoreModule)
}
]
}
];
#NgModule({
imports: [
CommonModule,
BrowserModule,
RouterModule.forRoot(routes , {
enableTracing: false
})
],
exports: [
RouterModule
],
})
export class AppRoutingModule { }
on core.module.ts -> This is working
import { RouterModule } from '#angular/router';
import { CommonModule } from '#angular/common';
import { CoreRoutes } from '../_config/route';
import { TableListComponent } from '../table-list/table-list.component';
import { TypographyComponent } from '../typography/typography.component';
import { IconsComponent } from '../icons/icons.component';
import { MapsComponent } from '../maps/maps.component';
import { NotificationsComponent } from '../notifications/notifications.component';
import { UpgradeComponent } from '../upgrade/upgrade.component';
import {UsersComponent} from '../users/user-list/users.component';
import {UserDetailsComponent} from '../users/user-details/user-details.component';
#NgModule({
imports: [
CommonModule,
RouterModule.forChild(CoreRoutes)
],
declarations: [
TableListComponent,
TypographyComponent,
IconsComponent,
MapsComponent,
NotificationsComponent,
UpgradeComponent,
UsersComponent,
UserDetailsComponent
],
providers : [
]
})
export class CoreModule {}
on route.ts - > in this case loadchildren only works if i include full path like this '../dashboard/dashboard.module#DashboardModule'
import { AuthGuard } from '../_helpers';
import {SandboxComponent, UsersComponent} from '../users/user-list/users.component';
import {UserDetailsComponent} from '../users/user-details/user-details.component';
export const CoreRoutes: Routes = [
{
path: 'dashboard',
loadChildren: () => import('../dashboard/dashboard.module').then(mod => mod.DashboardModule),
// '../dashboard/dashboard.module#DashboardModule'
canActivate: [AuthGuard],
},
{
path: 'users',
component: UsersComponent,
children: [
{ path: 'sandbox', component: SandboxComponent } // url: about/item
]
},
{
path: 'users/sandbox',
component: UsersComponent
},
{ path: 'user/:id', component: UserDetailsComponent }
];
ERROR in src\app\core\core.module.ts(18,31): Error during template compile of 'CoreModule'
Function expressions are not supported in decorators in 'CoreRoutes'
'CoreRoutes' contains the error at src\app\_config\route.ts(8,23)
Consider changing the function expression into an exported function.```
I find the problem with this.
The problem was when i started the server with --aot (Ahead Of Time) parameter and CLI version is 7.X , if i run simple like ng serve everything works (JIT - Just in time) compiler.
According there documents https://angular.io/guide/aot-compiler this is coming from 6 CLI version and something happens after update CLI to 7 / 8

raven - sentry + django = No servers configured, and sentry not installed. Cannot send message

I have a sentry server that works ok.
raven test <dnstoserver> -> Sending a test message... success!
I have a dev machine with django 1.3 and raven 1.93.
In the django project I have this:
setting.py:
SENTRY_KEY=<secretkey>
SENTRY_DNS=<dnstoserver>
INSTALLED_APPS = (
'bar',
'foo',
'raven.contrib.django',
)
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'root': {
'level': 'WARNING',
'handlers': ['sentry'],
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
},
'handlers': {
'sentry': {
'level': 'ERROR',
'class': 'raven.contrib.django.handlers.SentryHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'django.db.backends': {
'level': 'ERROR',
'handlers': ['console'],
'propagate': False,
},
'raven': {
'level': 'DEBUG',
'handlers': ['console', 'sentry'],
'propagate': False,
},
},
}
Mind the absence of 'sentry' in the installed_apps. This is intentionally, since sentry is the server and should not be on a client!
views.py (in a view):
import logging
logger = logging.getLogger("raven")
logger.error("test")
When I run the view I get on the console:
No servers configured, and sentry not installed. Cannot send message
Why, and how to fix?
Were you really setting SENTRY_DNS or SENTRY_DSN?
When you set SENTRY_DSN the instantiation of the major config variables happens automatically (including SENTRY_SERVERS, SENTRY_PUBLIC_KEY, SENTRY_SECRET_KEY, and SENTRY_PROJECT)
The problem was in the construction of the raven DjangoClient. It did not get passed any servers, and couldn't find sentry config to steal that config from.
I added in the settings.py:
SENTRY_SERVERS=<dnstoserver>
Console now outputs this every time raven is called:
INFO 2012-06-21 05:33:19,831 base 4323 140735075462336 Configuring Raven for host: <dnstoserver>
But it works like a charm! Messages in sentry...
BTW. for all the undocumented settings take a look in raven.contrib.django.models.get_client()
I suggest to use:
SENTRY_DSN = 'http://user:password#<domain>:<port>/<project_id>'
And in APPS_INSTALLED add:
'raven.contrib.django.raven_compat'
Also take a look at this guide:
http://code.fetzig.at/post/18607051916/sentry-and-raven-setup-for-django-projects

Resources