How to generate an Angular app in a custom Nx generator? - nrwl-nx

I have an Nx Angular monorepository. I want to implement a custom generator so I can create apps quickly. I'm able to generate libraries by using the libraryGenerator function, from #nrwl/workspace. My generator is looking like this so far:
import { Tree, formatFiles } from '#nrwl/devkit';
import { libraryGenerator } from '#nrwl/workspace';
export default async function (host: Tree, schema: App) {
await generateLibrary(host, schema, 'models', 'domain');
await generateLibrary(host, schema, 'data-access', 'data');
await formatFiles(host);
}
async function generateLibrary(
host: Tree,
schema: App,
libraryName: string,
type: string
) {
const directory = `${schema.system.toLowerCase()}/${schema.name}`;
const importPath = `#org/${schema.system.toUpperCase()}/${
schema.name
}/${libraryName}`;
await libraryGenerator(host, {
name: libraryName,
directory,
importPath,
linter: 'eslint',
simpleModuleName: true,
strict: true,
tags: `type:${type}', scope:${schema.scope}`,
});
}
Now, I want to generate apps as well, but I'm not sure how one does that, since there's nothing like an "app generator" coming out of #nrwl/workspace, nor from #nrwl/devkit.

You can use applicationGenerator from #nrwl/angular/generators.
import { applicationGenerator } from '#nrwl/angular/generators
....
....
....
await applicationGenerator(host, {
name: appName,
directory: directoryName,
style: 'scss',
tags: ``,
routing: false,
e2eTestRunner: E2eTestRunner.None,
});
If you are looking for generating nest application, you can use :
import { applicationGenerator } from '#nrwl/nest';
....
....
....
await applicationGenerator(host, {
name: appName,
unitTestRunner: 'jest',
linter: Linter.EsLint,
directory: directoryName,
tags: ``
});

Related

Strapi email designer plugin reference template to record

I'm currently developing a multi-tenant API with Strapi and for one of the parts I use the Strapi email designer plugin because I want to send some emails but I want them to be custom designed for each tenant, the problem is that the plugin's table is not accessible in the content manager of Strapi so I can only hard code the template to a specific endpoint, is there a way to have the plugin table in the content manager or for it to be referenced to a content manager table something like:
(table)tenant->(field)templateId => (ref-table)plugin-email-designer->(ref-field)templateId
you know so I can switch and set dynamically from the Strapi panel and not with hard-coded endpoints
I've checked your issue briefly, and there is option you are going to like, but it involves using patch-package...
So, let's assume that you have strapi project created and you have added strapi-plugin-email-designer and you are using yarn v1.xx.xx:
yarn add patch-package postinstall-postinstall
Go to node_modules/strapi-plugin-email-designer/server/content-types/email-template/schema.json
change following fileds:
{
...
"pluginOptions": {
"content-manager": {
"visible": true
},
"content-type-builder": {
"visible": true
}
},
...
}
now run
yarn patch-package strapi-plugin-email-designer
now open your projects package.json and add to scripts:
{
"scripts": {
...
"postinstall": "patch-package"
}
}
run
yarn build
yarn develop
head to admin ui, you should see new Collection:
so now you can do that:
Sending Email
Let's assume you added a relation has one called email_template to your model.
Next we need to add custom route, so in /src/api/tenant/routes/ create file called routes.js
/src/api/tenant/routes/routes.js
module.exports = {
routes: [
{
method: 'POST',
path: `/tenants/:id/send`,
handler: `tenant.send`
}
]
}
now, we need to add handler to controller:
/src/api/tenant/controllers/tenant.js
"use strict";
/**
* tenant controller
*/
const { createCoreController } = require("#strapi/strapi").factories;
module.exports = createCoreController("api::tenant.tenant", ({ strapi }) => ({
async send(ctx) {
const { id } = ctx.params;
const { data } = ctx.request.body;
// notice, if you need extra validation you add it here
// if (!data) return ctx.badRequest("no data was provided");
const { to, subject } = data;
const { email_template, ...tenant } = await strapi.db
.query("api::tenant.tenant")
// if you have extra relations it's better to populate them directly here
.findOne({ where: { id }, populate: ["email_template"] });
console.log(email_template);
try {
await strapi
.plugin("email-designer")
.service("email")
.sendTemplatedEmail(
{
to,
//from, < should be set in /config/plugins.js email.settings.defaultFrom
//replayTo < should be set in /config/plugins.js email.settings.defaultReplyTo
},
{
templateReferenceId: email_template.templateReferenceId,
subject,
},
{
...tenant,
// this equals to apply all the data you have in tenant
// this may need to be aligned between your tenant and template
}
);
return { success: `Message sent to ${to}` };
} catch (e) {
strapi.log.debug("📺: ", e);
return ctx.badRequest(null, e);
}
},
}));
don't forget to enable access to /api/tenants/:id/send in admin panel, Settings - Roles
POST http://localhost:1337/api/tenants/1/send
{
"data": {
"to" : "email#example.com",
"subject": "Hello World"
}
}
response:
{
"success": "Message sent to email#example.com"
}
pls note, there is no template validation, e.g. if you give it a wrong template it would not be happy

Why does my redirects() in NextJS not work?

what am I doing wrong? I'm building an accessible website with NextJS and want to redirect to fitting pages to the plain-language-counterpart. But since they are a different kind of language, their URLs are different, too.
My routes are built like this:
Standard language = my-website.com/about
Plain language = my-website.com/plain-language/about
And I have a switch where I can just change the /plain-language/ part
Now I have these routes:
my-website.com/accessible-webdesign
my-website.com/plain-language/for-disabled-persons
And if I click the switch on the first one, it will link me to my-website.com/plain-language/accessible-webdesign, which doesn't exist! So I used redirects() and also restarted my server to fix this, but it doesn't work. It doesn't redirect and I get a 404 just as before.
Can you check my code and tell me, what I should change to make it work?
Thank you!
This is my next.config.js:
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
/** #type {import('next').NextConfig} */
const path = require('path');
const withPWA = require('next-pwa')({
dest: 'public',
disable: process.env.NODE_ENV === 'development',
sw: 'sw.js'
})
const nextConfig = {
async redirects(){
return[
{
source: '/plain-language/accessible-webdesign',
destination: '/plain-language/for-disabled-persons',
permanent: 'true'
}
]
},
reactStrictMode: true,
swcMinify: true,
trailingSlash: false,
webpackDevMiddleware: config => {
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300
}
return config
},
sassOptions: {
includePaths: [path.join(__dirname, 'styles')]
},
experimental: {
images: {
layoutRaw: true
}
},
images: {
/*unoptimized: true - for static export!*/
/*deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
formats: ['image/webp']*/
}
}
module.exports = withBundleAnalyzer(withPWA({nextConfig}));
My working solution was from here: https://stackoverflow.com/a/58182678/
I put a middleware.ts in the root-folder (right next to package.json, next.config.js etc).
And I wrote this inside:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export async function middleware(request: NextRequest) {
/* /accessible-webdesign --> /for-disabled-persons */
if (request.nextUrl.pathname.startsWith('/plain-language/accessible-webdesign')) {
return NextResponse.redirect(new URL('/plain-language/for-disabled-persons', request.url));
}
/* /another-url --> /another-redirect */
if (request.nextUrl.pathname.startsWith('/plain-language/another-url')) {
return NextResponse.redirect(new URL('/plain-language/another-redirect', request.url));
}
}
Not as beautiful, but working.

Redirect Strapi admin index to admin login

I am currently looking for way to create a permanent 301 redirect from the default Strapi admin index route (ie strapidomain.com) to the configured admin route (ie strapidomain.com/admin).
I have explored utilizing a custom middleware by configuring the admin package:
Path: ./admin/middlewares/redirect/index.js
const path = require('path');
module.exports = strapi => {
return {
initialize: function(cb) {
strapi.router.get('/', (ctx) => {
ctx.redirect(strapi.config.get('server.admin.url', '/admin'))
});
}
};
};
I then activated the custom middleware with:
Path: ./admin/config/middleware.js
module.exports = {
settings: {
redirect: {
enabled: true
}
}
}
Unfortunately I can still hit the admin panel route without being redirected. Based on everything I have read, this should be possible however I have not been able to get this working.
Thoughts?
for newer version v4+
src/middlewares/redirector.js
module.exports = (config, {strapi}) => {
return async (ctx, next) => {
if (ctx.path === '/') {
ctx.redirect(strapi.config.get('server.admin.url', '/admin'));
return
}
await next()
};
};
config/middlewares.js
module.exports = [
{name: 'global::redirector'},
//...
]
The only issue here is that you just placed the redirect middleware within a admin folder which was absolutely not required. The middlewares folder should directly reside at the root of your project.
Correct the path from:
./admin/middlewares/redirect/index.js
To this:
./middlewares/redirect/index.js
I can show you what I've tried personally, below:
My implementation:
1. Create a directory in the root of your project
$ mkdir -p ./middlewares/redirector/
2. Create a index.js file in ./middlewares/redirector/ with the content as:
module.exports = () => {
return {
initialize() {
strapi.router.get('/', (ctx) => {
ctx.redirect(strapi.config.get('server.admin.url', '/admin'));
});
},
};
};
3. Finally enable the redirector middleware in the config/middleware.js file:
module.exports = {
settings: {
redirector: {
enabled: true,
},
},
};

Nuxt vuex - moving store from Vue

I have been fiddling with moving a tutorial I did in Vue to Nuxt. I have been able to get everything working, however I feel I'm not doing it the "proper way". I have added the Nuxt axios module, but wasnt able to get it working, so I ended up just using the usual axios npm module. Here is my store:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(Vuex)
Vue.use(VueAxios, axios)
export const state = () => ({
events: []
})
export const mutations = {
setEvents: (state, events) => {
state.events = events
}
}
export const actions = {
loadEvents: async context => {
let uri = 'http://localhost:4000/events';
const response = await axios.get(uri)
context.commit('setEvents', response.data)
}
}
I would like to know how to re-write this store using the #nuxtjs/axios module. I also didnt think I'd need to import vuex here, but if I dont, my app doesn't work.
Thanks for any help!
Using the #nuxtjs/axios module, you can configure axios inside your nuxt.config.js:
// nuxt.config.js
export default {
modules: [
'#nuxtjs/axios',
],
axios: {
// proxy: true
}
}
You can use it inside your store (or components) with this.$axios
// In store
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}
}

Nuxt.js - Implementing a component using Plugin

I would like to implement a custom Toaster component into my NuxtJs application by this method this.$toast.show({}) What is the best way of approaching this? Sadly I can't find any documentation on this.
Sorry, I arrive one year late...
I had the same proplem. Here is my code:
The index of my plugin (index.js ; Nofification.vue is a classical Vue component):
import Notifications from './Notifications.vue'
const NotificationStore = {
state: [], // here the notifications will be added
settings: {
overlap: false,
horizontalAlign: 'center',
type: 'info',
timeout: 5000,
...
},
setOptions(options) {
this.settings = Object.assign(this.settings, options)
},
removeNotification(timestamp) {
...
},
addNotification(notification) {
...
},
notify(notification) {
...
},
}
const NotificationsPlugin = {
install(Vue, options) {
const app = new Vue({
data: {
notificationStore: NotificationStore,
},
methods: {
notify(notification) {
this.notificationStore.notify(notification)
},
},
})
Vue.prototype.$notify = app.notify
Vue.notify = app.notify
Vue.prototype.$notifications = app.notificationStore
Vue.component('Notifications', Notifications)
if (options) {
NotificationStore.setOptions(options)
}
},
}
export default NotificationsPlugin
Here I call my plugin and inject it in Nuxt:
import Notifications from '~/components/NotificationPlugin'
Vue.use(Notifications)
export default (context, inject) => {
inject('notify', Vue.notify)
}
In my case, I use it in another plugin (nuxtjs axios).
import NOTIFICATIONS from '~/constants/notifications'
export default function ({ error, $axios, app }) {
// Using few axios helpers (https://axios.nuxtjs.org/helpers):
$axios.onError((axiosError) => {
// eslint-disable-next-line no-console
console.log('Axios: An error occured! ', axiosError, axiosError.response)
if (process.server) {
...
} else {
app.$notify({
message: 'Mon message',
timeout: NOTIFICATIONS.DEFAULT_TIMEOUT,
icon: 'tim-icons icon-spaceship',
horizontalAlign: NOTIFICATIONS.DEFAULT_ALIGN_HORIZONTAL,
verticalAlign: NOTIFICATIONS.DEFAULT_ALIGN_VERTICAL,
type: 'success',
})
console.log('PRINT ERROR')
return Promise.resolve(true)
}
})
}
As I injected it, I think I could have done export default function ({ error, $axios, app, $notify }) { and directly use $notify (and not the app.$notify).
If you want a better understanding, feel free to consult #nuxtjs/toast which works the same way:
https://github.com/nuxt-community/community-modules/blob/master/packages/toast/plugin.js
And the matching Vue component:
https://github.com/shakee93/vue-toasted/blob/master/src/index.js
Good luck, this is not easy stuff. I'll try to add something easier to understand in the docs!
you can find in this package https://www.npmjs.com/package/vue-toasted
installation
npm install vue-toasted --save
make a file as name toast.js in plugin folder
toast.js
import Vue from 'vue';
import Toasted from 'vue-toasted';
Vue.use(Toasted)
add this plugin to nuxt.config.js
plugins: [
{ src: '~/plugins/toast', ssr: false },
],
now you able to use in your methods like this
this.$toasted.show('hello i am your toast')
hope this helps