Generate an OpenAPI NestJs server stub - nestjs

I'm messing around with custom templates for the OpenAPI-Generator CLI to make a server stub for NestJs (controllers, services, mongoose model templates) and I can't seem to strip off the *Service for the classname mustache template.
For example:
import { Controller, Get, Post, Patch } from '#nestjs/common';
/**
#Controller('cats')
export class CatsController {
#Get()
findAll(): string {
return 'This action returns all cats';
}
}
*/
{{#operations}}
{{#description}}
/**
* {{&description}}
*/
{{/description}}
#Controller('{{classname}}')
export class {{classname}}Controller {
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}* #param {{paramName}} {{description}}
{{/allParams}}*/
{{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}): {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}};
{{/operation}}
}
{{/operations}}
I do like there is a nodejs-express template, but it isn't either typescript nor a framework like NestJs. As in it is a good starter, but not an end-goal for me.
Has anyone had any success or seen the templates for making a server stub and not an Axios client library.

Related

Can i use Prisma-Client as a nested dependency

I was making a restful APIs framework I decided to add Prisma for database support I want to provide Prisma-client to users in an appropriate way.
here is what I'm trying to do:
// #my/pkg
import {PrismaClient} from '#prisma/client'; // here the prisma client is nested dependency for client
// base class for all routes, the user will extend this class to create a route
abstract class BaseRouter {
public get (req: Request, res: Response): Promise <void> {}
public db = new PrimaClient ();
}
// client side
// note! prisma init and database will setup on client side
import BaseRouter from '#my/pkg'
class Client extends BaseRouter {
public get (req: Request, res: Response): Promise <void> {
const users = db.Users.findMany (); // I'm getting error here
}
}
so my question is can I use pirsma-client as a nested dependency and is there any way to achieve similar results?
Reason for that Design:
I'm providing database access from the base class because I also want to provide other databases like Redis, firebase, etc... according to the flavor of the database chosen by the user.
here how it looks like:-
which database do you want to choose for your app:
- Prisma (SQL/MongoDB)
- firebase (NON-SQL)
- Redis (caching)
According to APIS design, all databases will access through the base class object db.
Thanks in Advance

How to implement database first approach in Nest JS

I have three schemas(User, Account, Contact) these three schemas used to created a model and generate the migration files also Next, this migration file migrate the PostgreSQL Database this part successfully completed using Nest JS.
Next, Manually I created one table and added few columns in the table. In this table(model) I need automatically integrate in our Nest JS CODE is it possible?
So, I google it how to achieve this scenario this given one solution schema first approach.
In Nest JS used one Library that is GraphQL this library used to achieve schema first approach. I
tried this approach but I could not get the database model in our code.
Anyone tell me how to achieve this scenario
/Combining NestJS and Prisma provides a new level of type-safety that is impossible to achieve with any other ORM from the Node.js & TypeScript ecosystem. This example demonstrates how to use Prisma Client./
import { Injectable, OnModuleInit, INestApplication } from '#nestjs/common'
import { PrismaClient } from '#prisma/client'
#Injectable()
export class PrismaService extends PrismaClient
implements OnModuleInit {
async onModuleInit() {
await this.$connect();
}
async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => {
await app.close();
});
}
}

How to get FullURL with NestJS?

How do I get the full URL of the page that NestJS is processing?
(e.g. http://localhost:3000/hoge)
//
// If you implement it with express, it looks like this.
// e.g. http://localhost:3000/hoge
//
function getFullUrl(req: express.Request) {
return `${req.protocol}://${req.get('Host')}${req.originalUrl}`;
}
You can inject the request-object using the Req() decorator allowing you to do pretty much the same thing you did in your pure express-app.
import {Controller, Get, Req} from '#nestjs/common';
import {Request} from 'express';
#Controller()
export class AppController {
#Get()
getHello(#Req() req: Request): void {
console.log(`${req.protocol}://${req.get('Host')}${req.originalUrl}`);
}
}
This of course assumes that you're using Express as your http-adapter (which is the default).

Import contentful in to react-native

I am extremely excited about using contentful for my project, but I can't get the JS library to work in a react-native project.
I get the following error:
I have tried the following approaches:
import contentful from 'contentful';
// or
var contentful = require('contentful');
You can reproduce the bug by going to this repo and following the steps I have provided.
Help would be greatly appreciated.
I am maintaining the Contentful sdk. I've put together a simple example
that shows how to use the SDK in React Native, you can check it here
It is basically getting a list of items from one of our example spaces and display the names in a ListView.Check indes.ios.js.
It looks like there is something wrong with the caching in your machine or so.
Anyway I hope this helps.If you have more problems please feel free to create issues in our github page
[UPDATE]
you can now configure the axios instance used in the SDK to use a different adapter. You can pass that when calling createClient
adapter: config => {
config.adapter = null // this is important if it is passing to another axios instance
// an http client combatible with React Native
return fetch(config)
}
Best,
Khaled
I've tried every option and it will never work using the Contentful SDK.
However, you can get it with REST and transform the response using the types from the contentful lib.
import axios from 'axios';
import {EntryCollection} from 'contentful';
import Env from '../Env';
const contentfulApi = 'https://cdn.contentful.com';
/**
* Default locale used in contentful calls
*
* #see {#link getContentfulEntries}
* #constant
*/
export const ContentfulLocale = 'sv';
/**
* #typedef ContentfulProps
* #param locale optional locale to use. Default is {#link ContentfulLocale}
* #param entryType content type in contentful model
*/
type ContentfulProps = {
entryType: string;
locale?: string;
};
/**
* Get entries from Contentful content API
* #param props See {#link ContentfulProps}
*/
export const getContentfulEntries = async <T>(
props: ContentfulProps,
): Promise<EntryCollection<T>> => {
const client = axios.create({
baseURL: `${contentfulApi}/spaces/${Env.CONTENTFUL_SPACEID}/environments/master/entries?`,
timeout: 1000,
headers: {Authorization: `Bearer ${Env.CONTENTFUL_TOKEN}`},
});
const result = await client.get<EntryCollection<T>>(
'&content_type=' + props.entryType,
);
return result.data;
};
export default getContentfulEntries;
I think the best way to use Contentful APIs with React Native is to use Apollo client and graphQL packages.
I worked around the same and get it done.
Install Apollo client and GraphQL npm package
npm install #apollo/client graphql
Install react-native async storage to store cache
npm install #react-native-async-storage/async-storage
Install apollo cache persist to persist the cache
npm install apollo3-cache-persist
you can read apollographql official documents for implementation
Create ApolloClient in the app.tsx/.js file
import { ApolloClient, ApolloProvider, InMemoryCache } from '#apollo/client';
const cache = new InMemoryCache();
const client = new ApolloClient({
uri: 'https://graphql.contentful.com/content/v1/spaces/{SPACE_ID}',
cache,
credentials: 'same-origin',
headers: {
Authorization: `Bearer {CDA-Access-Token}`,
},
});
Wrap all components in ApolloProvider
const App = () => {
const [loadingCache, setLoadingCache] = useState(true);
useEffect(() => {
persistCache({
cache,
storage: AsyncStorage,
}).then(() => setLoadingCache(false));
}, []);
if (loadingCache) {
return <Loader />;
}
return (
<ApolloProvider client={client}>
<SafeAreaView style={{flex: 1}}>
<Posts />
</SafeAreaView>
</ApolloProvider>
);
};
export default App;
Import gql and useQuery to fetch data
import { gql, useQuery } from '#apollo/client';
Now, write GraphQL query
const QUERY_COLLECTION = gql`
{
postsCollection {
items {
title
author
publishDate
inshorts
featuredImage {
url
}
}
}
}
`;
Fetch data using useQuery function
const { data, loading } = useQuery(QUERY_COLLECTION);
That's all to fetch data from Contentful in React Native App.
To read this in detailed, have a look to this post

Augmenting existing interfaces

This isn't a specific koa question even though all the code is using koa, I'm just new to node and the module system.
When using Koa every request is defined by the Request interface:
declare module "koa" {
namespace Koa {
...
export interface Request {
...
}
...
}
...
namespace Koa {}
export = Koa;
}
I'm using the bodyparser middleware so Request has a property named body but typescript is unaware of this and so I'm trying to add that by adding this definition file as a reference:
/// <reference path="globals/koa/index.d.ts" />
/// <reference path="koa.d.ts" />
import koa = require("koa");
...
app.use(ctx => {
console.log(ctx.request.body); // error: Property 'body' does not exist on type 'Request'
});
Where koa.d.ts is:
declare module "koa" {
namespace Koa {
export interface Request {
body: any;
}
}
export default Koa;
}
But this is probably the wrong way to do it as it's not working.
How can it be done?
Thanks.
I just had to work through this. I added this to my custom-typings.d.ts:
import {Request} from "koa";
declare module "koa" {
interface Request {
body: any;
}
}
Just ran into this. I found that since I was using koa-bodyparser middleware, I needed to install the #types/koa-bodyparser module which augments the interface for you - https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/koa-bodyparser/index.d.ts#L20.
import * as bodyparser from 'koa-bodyparser';
...
app.use(bodyParser());
Then, in your route, "body" will be available on the request object.
ctx.request.body

Resources