Accessing context from this - this

I have a middleware that exports context.isMobile. I can access it from layout like this:
layout (ctx) {
if(ctx.isMobile) {
return 'mobile'
} else if (ctx.isDesktop) {
return 'default'
}
},
...but I can't access the context from data or computed. How do I get the context there?

You can access the context via this.$nuxt.context like this:
export default {
data() {
console.log(this.$nuxt.context)
return { /*...*/ }
},
computed: {
myProp() {
console.log(this.$nuxt.context)
return 'foo'
}
}
}

Related

two tiptap2 custom extensions that extend TextStyle

In tiptap2, I have two custom extensions that add a class versus a style because I am utilizing tailwindcss, which leverages classes exclusively, not inline styles.
So, the first one adds 'class="text-green-500"' (or whatever) and likewise, 'class="bg-green-500"'. I extend TextStyle in both custom extensions to allow for class versus span. I believe the answer lies in extending textstyle once, but I'm not sure how to go about that and catch both outcomes.
I can't combine the two by having a highlight span and a color span together.
If I take the following:
and then try and say make the "w" a different color, I get:
What I want to achieve is "Howdy" with complete cyan while still able to apply individual font colors within the outer span (or vice-versa).
import { TextStyle } from '#tiptap/extension-text-style';
export const HighlightColorStyle = TextStyle.extend({
parseHTML() {
return [
{
tag: 'span',
getAttrs: (node) => /text|bg-[\w]*-[1-9]00/.test(node.className)
}
];
}
});
export const HighlightColor = Extension.create({
name: 'highlightColor',
addGlobalAttributes() {
return [
{
types: ['textStyle'],
attributes: {
class: {
default: ''
}
}
}
];
},
addCommands() {
return {
setHighlightColor:
(color) =>
({ chain }) => {
console.log('hoadodoadfaf', color);
return chain().setMark('textStyle', { class: color });
},
toggleHighlightColor:
() =>
({ chain }) => {
return chain().toggleMark('textStyle');
},
unsetHighlightColor:
() =>
({ chain }) => {
return chain().setMark('textStyle', { class: null }).removeEmptyTextStyle();
}
};
}
});
and
import { Extension } from '#tiptap/core';
import { TextStyle } from '#tiptap/extension-text-style';
export const TextColorStyle = TextStyle.extend({
parseHTML() {
return [
{
tag: 'span',
getAttrs: node => /text-[\w]*-[1-9]00/.test(node.className)
}
];
}
});
export const TextColor = Extension.create({
name: 'textColor',
addGlobalAttributes() {
return [
{
types: ['textStyle'],
attributes: {
class: {
default: ''
} }
}
];
},
addCommands() {
return {
setTextColor:
color =>
({ chain }) => {
console.log('hoadodoadfaf', color)
return chain().setMark('textStyle', { class: color });
},
toggleTextColor:
() =>
({ chain }) => {
return chain().toggleMark('textStyle');
},
unsetTextColor:
() =>
({ chain }) => {
return chain().setMark('textStyle', { class: null }).removeEmptyTextStyle();
}
};
}
});
You should treat class as object not string, so the multi class can combine, then add a ClassExtension to apply the class to a tag.
The ClassExtension is works like textStyle, except it will apply the class, textStyle dose not apply styles, because styles is an object, applied by individual Extension.
Write a simple classNames extension based on a modified testStyle extension.

Setting up jest mocks - one way works the other doesn't

When setting up jest mocks for a class what does not work for me with an error of "_TextObj.TextObj is not a constructor" is
import { TextObj, } from "#entities/TextObj";
jest.mock('#entities/TextObj', () => {
return jest.fn().mockImplementation((config: TextObjConfig) => {
return { ...
}
});
});
According to https://jestjs.io/docs/es6-class-mocks#calling-jestmock-with-the-module-factory-parameter I had expected the first version to work too - or not?
however what works is
import { TextObj, } from "#entities/TextObj";
jest.mock('#entities/TextObj');
...
beforeAll(() => {
TextObj.mockImplementation((config: TextObjConfig) => {
return {
..
}
});
});
TextObj is a named export and you're trying to mock default export which is why it is throwing the error _TextObj.TextObj is not a constructor.
For mocking named export, you need to do following the changes i.e return an object that contains TestObj property:
import { TextObj, } from "#entities/TextObj";
jest.mock('#entities/TextObj', () => {
TestObj: jest.fn().mockImplementation((config: TextObjConfig) => {
return { ...
}
});
});

Is it possible to override the DEFAULT_TEARDOWN function inside exceptions-zone.ts?

I'm trying to create an application with NestJS framework and I'd like to check if a specific Service is in the application context but, the framework default behavior is exiting the process when it doesn't find the Service inside the context.
I've surrounded the get method with try...catch but it doesn't work because of the process.exit(1) execution.
private async loadConfigService(server: INestApplication): Promise<void> {
try {
this.configService = await server.get<ConfigService>(ConfigService, { strict: false });
} catch (error) {
this.logger.debug('Server does not have a config module loaded. Loading defaults...');
}
this.port = this.configService ? this.configService.port : DEFAULT_PORT;
this.environment = this.configService ? this.configService.environment : Environment[process.env.NODE_ENV] || Environment.DEVELOPMENT;
this.isProduction = this.configService ? this.configService.isProduction : false;
}
I'd like to catch the exception to manage the result instead of exiting the process.
Here's what I came up with:
import { NestFactory } from '#nestjs/core';
export class CustomNestFactory {
constructor() {}
public static create(module, serverOrOptions, options) {
const ob = NestFactory as any;
ob.__proto__.createExceptionZone = (receiver, prop) => {
return (...args) => {
const result = receiver[prop](...args);
return result;
};
};
return NestFactory.create(module, serverOrOptions, options);
}
}
Now, instead of using the default NestFactory I can use my CustomNestFactory
Dirty, but it works
Here is my code to solve same issue:
import { ExceptiinsZone } from '#nestjs/core/errors/exceptions-zone';
ExceptionsZone.run = callback => {
try {
callback();
} catch (e) {
ExceptionsZone.exceptionHandler.handle(e);
throw e;
}
};
You may need to override asyncRun() also for other method.

vuejs nextick don't update

i try to connect my frontend to my backend,
the request is done correctly i received the correct data, but the DOM is not updating. I use this.$nextTick but it doesn't affect the update
in the template i use {{ system.CPU.avgload }}
like i said the fetch is done correctly it pass into nexttick, but nothing change
in the main vue i have this
import System from '../utils/system'
import Auth from '../utils/auth'
export default {
created: function () {
this.system = {
CPU: {
avgload: 0
}
}
},
mounted: function () {
this.fetchData()
setInterval(function () {
this.fetchData()
}.bind(this), 10000)
},
methods: {
fetchData () {
if (!Auth.checkAuth) {
console.log('test')
this.error = true
} else {
var self = this
this.$nextTick(function () {
System.Get(function (response) {
self.system = response
})
})
}
}
}
}
and the template is
<div class="text-xs-left" id="example-caption-1">CPU : {{ system.CPU.avgload }} %</div>
You have to add variable system in the data section of vue instance. Than only this variable will become reactive and available in the HTML.
export default {
data: function () {
return { system: {
CPU: {
avgload : ""
}
}
}
}
...
...

Magento2 Override existing js component

I want to override the existing magento2 JS Component in my theme for some more customization.
Magento_Checkout/js/view/minicart.js
Above JS component i want to override and i want to add some more operation on the remove button event.
You can try "map" of require js. I used this and working for me. following is the requirejs-config.js inside my theme.
var config = {
map: {
'*': {
'Magento_Checkout/js/view/minicart':'js/custom/minicart'
}
}
};
Modified minicart.js file is placed inside "web/js/custom" folder inside my theme.
Just Go to your theme Override Magento_Checkout there, then under web folder make path as same as core module then add your js file & do required changes. It will reflect on frontend.
You can also extend an existing Magento JS without overwriting the whole file in your module add the require-config.js
app/code/MyVendor/MyModule/view/frontend/requirejs-config.js
var config = {
config: {
mixins: {
'Magento_Checkout/js/view/minicart': {
'MyVendor_MyModule/js/minicart': true
}
}
}
};
Then add the minicart.js
app/code/MyVendor/MyModule/view/frontend/web/js/minicart.js
define([], function () {
'use strict';
return function (Component) {
return Component.extend({
/**
* #override
*/
initialize: function () {
var self = this;
return this._super();
},
MyCustomFunction: function () {
return "my function";
}
});
}
});
define(['jquery'],function ($) {
'use strict';
var mixin = {
/**
*
* #param {Column} elem
*/
initSidebar: function () {
var sidebarInitialized = false, miniCart;
miniCart = $('[data-block=\'minicart\']');
if (miniCart.data('mageSidebar')) {
miniCart.sidebar('update');
}
if (!$('[data-role=product-item]').length) {
return false;
}
miniCart.trigger('contentUpdated');
if (sidebarInitialized) {
return false;
}
sidebarInitialized = true;
miniCart.sidebar({
'targetElement': 'div.block.block-minicart',
'url': {
'checkout': window.checkout.checkoutUrl,
'update': window.checkout.updateItemQtyUrl,
'remove': window.checkout.removeItemUrl,
'loginUrl': window.checkout.customerLoginUrl,
'isRedirectRequired': window.checkout.isRedirectRequired
},
'button': {
'checkout': '#top-cart-btn-checkout',
'remove': '#mini-cart a.action.delete',
'increacseqty':'#mini-cart a.action.increase-qty',
'decreaseqty':'#mini-cart a.action.decrease-qty',
'close': '#btn-minicart-close'
},
'showcart': {
'parent': 'span.counter',
'qty': 'span.counter-number',
'label': 'span.counter-label'
},
'minicart': {
'list': '#mini-cart',
'content': '#minicart-content-wrapper',
'qty': 'div.items-total',
'subtotal': 'div.subtotal span.price',
'maxItemsVisible': window.checkout.minicartMaxItemsVisible
},
'item': {
'qty': ':input.cart-item-qty',
'button': ':button.update-cart-item'
},
'confirmMessage': $.mage.__('Are you sure you would like to remove this item from the shopping cart??')
});
return this._super();
}
};
return function (minicart) { // target == Result that Magento_Ui/.../columns returns.
return minicart.extend(mixin); // new result that all other modules receive
};
});

Resources