In Deno it is possible to version the dependencies in the import statement, and there's no package.json like with npm.
But how to managed it's URLs and versions in a single place?
I will have multiple files and dependencies that will be declared all over my system.
For example:
dateUtils.ts
import { parseDate } from 'https://deno.land/std#0.50.0/datetime/mod.ts';
const DEFAULT_MASK = "dd-mm-yyyy";
export function parse(date: string): Date {
return parseDate(date, DEFAULT_MASK);
};
service.ts
import { v4 } from "https://deno.land/std/uuid/mod.ts";
export function process(request: any) {
const { token } = request;
const isValid = v4.validate(token);
console.log(`Token validity: ${isValid}`)
};
app.ts
import { parse } from "./dateUtil.ts";
import * as service from "./service.ts";
const date = parse("20-05-2020");
console.log(date);
const request = {
token: "408d30e5-1e90-45e3-b299-6520feee6d76"
}
service.process(request)
To avoid typing https://deno.land/std/uuid/mod.ts everywhere you can use import maps
// import_map.json
{
"imports": {
"http/": "https://deno.land/std/http/"
}
}
// server.ts
import { serve } from "http/server.ts";
const body = new TextEncoder().encode("Hello World\n");
for await (const req of serve(":8000")) {
req.respond({ body });
}
deno run --importmap=import_map.json --allow-net server.ts
import maps are currently unstable, but you can use them behind --unstable flag.
Aside from that it's common to have a deps.ts file where you'll re-export all your dependencies.
// deps.ts
export * as path from "https://deno.land/std#0.51.0/path/mod.ts";
// other exports .. from
// some other file
import { path } from './deps.ts' // instead of "https://deno.land/std#0.51.0/path/mod.ts"
path.basename('/bar/test.txt');
In deno there is a convention for consolidating imports into deps.ts.
export { parseDate } from 'https://deno.land/std#0.50.0/datetime/mod.ts';
export { v4 } from "https://deno.land/std/uuid/mod.ts";
Exports can then be imported in other modules/scripts on your application:
import { v4 } from "./deps.ts";
import { parseDate } from './deps.ts';
const myUUID = v4.generate();
parseDate("20-05-2020", "dd-mm-yyyy")
When using this approach one should consider integrity checking & lock files:
// Add a new dependency to "src/deps.ts", used somewhere else.
export { xyz } from "https://unpkg.com/xyz-lib#v0.9.0/lib.ts";
# Create/update the lock file "lock.json".
deno cache --lock=lock.json --lock-write src/deps.ts
# Include it when committing to source control.
git add -u lock.json
git commit -m "feat: Add support for xyz using xyz-lib"
git push
Related
I have the middleware.js file within /myproject/pages/middleware.js:
export function middleware(request) {
console.log(1);
return NextResponse.redirect(new URL('/', request.url));
}
// See "Matching Paths" below to learn more
export const config = {
matcher: ['/test'],
};
Now what I expect is when i go to the page /test then it should redirect me to /. However nothing happens and I see my standard 404 page.
Any ideas why?
NextJs version: 12.2.2
Latest versions of NextJS requires user to have a single middleware on the root folder.
Instead of {root}/pages/_middleware.js, try {root}/middleware.js
For next 13.0.2 / 13.0.1
if you are using appDir: true ( experimental )
if you want to hit middleware:
put middleware.ts in root project:
( as the same hierarchy as "app" folder, not inside app folder... )
make sure tsconfig has include: [..., "middleware.ts"]
make empty "pages" folder. ( based on issue )
will hit every request:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest ) {
console.log('lol!!!')
}
export const config = {
matcher: '/',
}
if your pages and middleware are not on the same level, then it won't work.
here is an example of middleware working with Cookies.
import { NextResponse } from "next/server";
export default function middleware(req){
let verify = req.cookies.get("loggedin");
let url = req.url
if(!verify && url.includes('/dashboard')){
return NextResponse.redirect("http://localhost:3000/");
}
if (verify && url === "http://localhost:3000/") {
return NextResponse.redirect("http://localhost:3000/dashboard");
}
}
I am new prisma / nextjs user and I am trying to understand how to unit test an API route that uses prisma. I have read the unit testing guide.
I like the dependency injection approach and have started trying to implement it. However I am struggling with the following development issue. Can anybody help?
With the dependency injection approach the unit testing guide explains how to setup the mock context and use this in the data access layer. Does anyone have any examples of how and where the real context could be initialised and used with an API route that uses a repository pattern? Is it possible to expand the next.js api handler with middleware to include the context to facilitate testing?
import type { NextApiRequest, NextApiResponse } from 'next'
import { PublishRepository } from '../../../repository'
// PUT /api/publish/:id
export default async function handle(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method == 'PUT') {
const postId = req.query.id;
let repo = new PublishRepository( // where does the live context come from and how is it initialised??? )
const post = repo.set_published(postId)
res.json(post);
}
}
Repository - Initialised using Context instance - How is this initialise for development and how is it mocked?
import { Post, PrismaClient } from "#prisma/client"
import { Context } from "../context"
import prisma from "lib/prisma"
export class PublishRepository {
private prisma: PrismaClient
constructor(context: Context) {
this.prisma = context.prisma
}
async set_published(post_id: string | string[]): Promise<Post> {
return await prisma.post.update({
where: { id: Number(post_id) },
data: { published: true },
});
}
}
I'm trying to build an app with meteor, apollo/graphql for the first time and the tutorial I'm watching might have outdated versions of apollo. I set up my server as:
import { createApolloServer } from "meteor/apollo";
import { makeExecutableSchema } from "graphql-tools";
const typeDefs = `
type Query {
hi: String
}
`;
const resolvers = {
Query: {
hi() {
return "Hello world";
}
}
};
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
createApolloServer({ schema });
However I usually get this as an error:
TypeError: graphqlExpress is not a function
I know it has to do with the apollo package, but I don't know how to get the migration changes made for apollo 2.0.0 into the meteor/apollo file from the migration doc on apollo's site. Any help is appreciated!
Created a next.js full stack application. After production build when I run next start it returns 500 : internal server. I'm using environment varibles for hitting api.
env.development file
BASE_URL=http://localhost:3000
It was working fine in development
service.ts
import axios from 'axios';
const axiosDefaultConfig = {
baseURL: process.env.BASE_URL, // is this line reason for error?
headers: {
'Access-Control-Allow-Origin': '*'
}
};
const axio = axios.create(axiosDefaultConfig);
export class Steam {
static getGames = async () => {
return await axio.get('/api/getAppList');
};
}
Do you have a next.config.js file?
To add runtime configuration to your app open next.config.js and add the publicRuntimeConfig and serverRuntimeConfig configs:
module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
To get access to the runtime configs in your app use next/config, like so:
import getConfig from 'next/config'
// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)
function MyImage() {
return (
<div>
<img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
</div>
)
}
export default MyImage
I hope this helps.
I dont think you have setup env.
You need to configure it for it to work. Try it without it and it should work fine!
I have a collection named LibraryItems which is available on both client and server side.
api/libraryitems/libraryitems.js
import { Mongo } from 'meteor/mongo';
const LibraryItems = new Mongo.Collection('libraryitems');
export default LibraryItems;
Instead of an if (Meteor.isServer) {..} publication in this same file, I would like to have a server folder with the specific publications:
api/libraryitems/server/publications.js
import LibraryItems from '../libraryitems';
import { Meteor } from 'meteor/meteor';
Meteor.publish('LibraryItems.pub.all', function () {
return LibraryItems.find({});
});
But somehow, against my expectations, this publication is not available...
update
This is my subscription code (meteor+reactjs):
./imports/ui/Library.js
import LibraryItems from '../api/libraryitems/libraryitems';
import { createContainer } from 'meteor/react-meteor-data';
...
export default createContainer(() => {
Meteor.subscribe('LibraryItems.pub.all');
var libraryitems = LibraryItems.find().fetch();
return {
libraryitems: libraryitems
}
}, Library);
You are exporting LibraryItems as a default export, that means when you import it you don't need curly brackets around it.
Change your import to:
import LibraryItems from '../libraryitems';
Also, clean up the publication code slightly:
return LibraryItems.find({});
EDIT
Now that you have posted your subscription code as requested, I see that you are subscribing to the publication with a different name.
Change to:
Meteor.subscribe('LibraryItems.all');
Hope that helps
I forgot to register the publications in mains.js:
import '../imports/api/libraryitems/server/publications';